diff options
author | kaihlavi <l.kaihlavirt@partner.samsung.com> | 2019-02-15 15:20:52 +0200 |
---|---|---|
committer | kaihlavi <l.kaihlavirt@partner.samsung.com> | 2019-02-15 15:20:52 +0200 |
commit | c88d4cc4e21e5659f0ab57a38f3ba29ab4b3c044 (patch) | |
tree | 7ecc0573137f79dd25ece3228a7199ebe150de47 /POLICY-SDK-APP | |
parent | ff9a74cf320a5f092ca4135375b5b80e35b441b1 (diff) |
Reformat POLICY-SDK-APP test cases
Reformat test cases to follow ONAP style
https://wiki.onap.org/display/DW/Java+code+style
Format changes mainly consist of conversions of tabs to 4 spaces
Samsung modifications copyrights added
Change-Id: I60b666d879960c80c80f8b1c41fc98fd0703f4d4
Issue-ID: POLICY-1506
Signed-off-by: kaihlavi <l.kaihlavirt@partner.samsung.com>
Diffstat (limited to 'POLICY-SDK-APP')
19 files changed, 2767 insertions, 2593 deletions
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java index e97e89eae..a06afc997 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,9 +25,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; - import java.io.File; - import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @@ -33,45 +33,63 @@ import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CheckPDPTest { - @Test - public final void test1NoPropertySet() { - try { - System.clearProperty("xacml.rest.pdp.idfile"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + @Test + public final void test1NoPropertySet() { + try { + System.clearProperty("xacml.rest.pdp.idfile"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "idonotexist.properties"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "doesnothaveproperties.atall"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "testbad.properties"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "idonotexist.properties"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "empty.properties"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "doesnothaveproperties.atall"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "testnotenoughvalues.properties"); + assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "testbad.properties"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "empty.properties"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "testnotenoughvalues.properties"); - assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - - assertNull(CheckPDP.getPdpMap()); - assertNull(CheckPDP.getEncoding("http://localhost:8082/pdp/")); + assertNull(CheckPDP.getPdpMap()); + assertNull(CheckPDP.getEncoding("http://localhost:8082/pdp/")); - } catch (Exception e) { - fail("Error occured in CheckPDP test"); - } - } - - @Test - public final void test2CheckPDP() { - try { - System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "test.properties"); - assertTrue(CheckPDP.validateID("http://localhost:8082/pdp/")); - assertTrue(CheckPDP.getPdpMap().containsKey("http://localhost:8082/pdp/")); - assertTrue(CheckPDP.getEncoding("http://localhost:8082/pdp/").equals("dGVzdHBkcDphbHBoYTQ1Ng==")); - } catch (Exception e) { - fail("Error occured in CheckPDP test"); - } - } + } catch (Exception e) { + fail("Error occured in CheckPDP test"); + } + } + @Test + public final void test2CheckPDP() { + try { + System.setProperty("xacml.rest.pdp.idfile", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "test.properties"); + assertTrue(CheckPDP.validateID("http://localhost:8082/pdp/")); + assertTrue(CheckPDP.getPdpMap().containsKey("http://localhost:8082/pdp/")); + assertTrue(CheckPDP.getEncoding("http://localhost:8082/pdp/") + .equals("dGVzdHBkcDphbHBoYTQ1Ng==")); + } catch (Exception e) { + fail("Error occured in CheckPDP test"); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java index bda2de1d0..7bd3be440 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,18 +23,15 @@ package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; - import java.io.BufferedReader; import java.io.File; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; @@ -54,32 +53,32 @@ import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.mock.web.MockHttpServletResponse; -public class PolicyManagerServletTest extends Mockito{ - - private static Logger logger = FlexLogger.getLogger(PolicyManagerServletTest.class); - private List<String> headers = new ArrayList<String>(); - - private static List<Object> rolesdata; - private static List<Object> basePolicyData; - private static List<Object> policyEditorScopes; - private static List<Object> policyVersion; - private static CommonClassDao commonClassDao; - private ConfigurationDataEntity configurationEntity; - private HttpServletRequest request; - private MockHttpServletResponse response; - - @Before - public void setUp() throws Exception{ - logger.info("setUp: Entering"); - - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - - PolicyController.setjUnit(true); - UserInfo userinfo = new UserInfo(); - userinfo.setUserLoginId("Test"); - userinfo.setUserName("Test"); - //Roles Data +public class PolicyManagerServletTest extends Mockito { + + private static Logger logger = FlexLogger.getLogger(PolicyManagerServletTest.class); + private List<String> headers = new ArrayList<String>(); + + private static List<Object> rolesdata; + private static List<Object> basePolicyData; + private static List<Object> policyEditorScopes; + private static List<Object> policyVersion; + private static CommonClassDao commonClassDao; + private ConfigurationDataEntity configurationEntity; + private HttpServletRequest request; + private MockHttpServletResponse response; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + + PolicyController.setjUnit(true); + UserInfo userinfo = new UserInfo(); + userinfo.setUserLoginId("Test"); + userinfo.setUserName("Test"); + // Roles Data rolesdata = new ArrayList<>(); Roles roles = new Roles(); roles.setLoginId("Test"); @@ -93,16 +92,17 @@ public class PolicyManagerServletTest extends Mockito{ roles1.setScope("['com','Test']"); rolesdata.add(roles); rolesdata.add(roles1); - - //PolicyEntity Data + + // PolicyEntity Data basePolicyData = new ArrayList<>(); String policyContent = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils + .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyContent); @@ -114,8 +114,8 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); basePolicyData.add(entity); - - //PolicyEditorScopes data + + // PolicyEditorScopes data policyEditorScopes = new ArrayList<>(); PolicyEditorScopes scopes = new PolicyEditorScopes(); scopes.setScopeName("com"); @@ -127,8 +127,8 @@ public class PolicyManagerServletTest extends Mockito{ scopes1.setUserModifiedBy(userinfo); policyEditorScopes.add(scopes); policyEditorScopes.add(scopes1); - - //PolicyVersion data + + // PolicyVersion data policyVersion = new ArrayList<>(); PolicyVersion policy = new PolicyVersion(); policy.setPolicyName("com\\Config_SampleTest1206"); @@ -137,146 +137,173 @@ public class PolicyManagerServletTest extends Mockito{ policy.setCreatedBy("Test"); policy.setModifiedBy("Test"); policyVersion.add(policy); - + HttpSession mockSession = mock(HttpSession.class); User user = new User(); - user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); - Mockito.when(request.getSession(false)).thenReturn(mockSession); - commonClassDao = mock(CommonClassDao.class); - - } - - @Test - public void testInit(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); - ServletConfig servletConfig = mock(ServletConfig.class); + user.setOrgUserId("Test"); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) + .thenReturn(user); + Mockito.when(request.getSession(false)).thenReturn(mockSession); + commonClassDao = mock(CommonClassDao.class); + + } + + @Test + public void testInit() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); - System.setProperty("xacml.rest.admin.closedLoopJSON", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json"); - servlet.init(servletConfig); - - assertTrue(PolicyManagerServlet.getServiceTypeNamesList().size() > 0); - assertTrue(PolicyManagerServlet.getPolicyNames().size() > 0); - - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } - } - - @Test - public void testBadInitJson() { - PolicyManagerServlet servlet = new PolicyManagerServlet(); - ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getInitParameterNames()) + .thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("xacml.admin.properties"); + System.setProperty("xacml.rest.admin.closedLoopJSON", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "JSONConfig.json"); + servlet.init(servletConfig); + + assertTrue(PolicyManagerServlet.getServiceTypeNamesList().size() > 0); + assertTrue(PolicyManagerServlet.getPolicyNames().size() > 0); + + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } + } + + @Test + public void testBadInitJson() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); - System.setProperty("xacml.rest.admin.closedLoopJSON", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.foo"); - servlet.init(servletConfig); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } - } - - @Test - public void testBadInitJsonInvalidFile() { - PolicyManagerServlet servlet = new PolicyManagerServlet(); - ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getInitParameterNames()) + .thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("xacml.admin.properties"); + System.setProperty("xacml.rest.admin.closedLoopJSON", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "JSONConfig.foo"); + servlet.init(servletConfig); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } + } + + @Test + public void testBadInitJsonInvalidFile() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); - System.setProperty("xacml.rest.admin.closedLoopJSON", new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "IDonotExist.json"); - servlet.init(servletConfig); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } - } - - @SuppressWarnings("static-access") - @Test - public void testDescribePolicy(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + when(servletConfig.getInitParameterNames()) + .thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("xacml.admin.properties"); + System.setProperty("xacml.rest.admin.closedLoopJSON", + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + + "test" + File.separator + "resources" + File.separator + + "IDonotExist.json"); + servlet.init(servletConfig); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } + } + + @SuppressWarnings("static-access") + @Test + public void testDescribePolicy() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); - BufferedReader reader = new BufferedReader(new StringReader("{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}")); + BufferedReader reader = new BufferedReader(new StringReader( + "{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}")); try { - when(request.getReader()).thenReturn(reader); - String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; - when(controller.getDataByQuery(query, null)).thenReturn(basePolicyData); - servlet.setPolicyController(controller); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } - } - - - @SuppressWarnings("static-access") - @Test - public void testPolicyScopeList(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + when(request.getReader()).thenReturn(reader); + String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; + when(controller.getDataByQuery(query, null)).thenReturn(basePolicyData); + servlet.setPolicyController(controller); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } + } + + + @SuppressWarnings("static-access") + @Test + public void testPolicyScopeList() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); list.add("{params: { mode: 'LIST', path: '/', onlyFolders: false}}"); list.add("{params: { mode: 'LIST', path: '/com', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("from PolicyEditorScopes", null)).thenReturn(policyEditorScopes); - when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like :scopeName", null)).thenReturn(policyEditorScopes); - when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like :scopeName", null)).thenReturn(policyVersion); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery("from PolicyEditorScopes", null)) + .thenReturn(policyEditorScopes); + when(controller.getDataByQuery( + "from PolicyEditorScopes where SCOPENAME like :scopeName", null)) + .thenReturn(policyEditorScopes); + when(controller.getDataByQuery( + "from PolicyVersion where POLICY_NAME like :scopeName", null)) + .thenReturn(policyVersion); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editBasePolicyTest(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + } + + @SuppressWarnings("static-access") + @Test + public void editBasePolicyTest() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(basePolicyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(basePolicyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editBRMSParamPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editBRMSParamPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString(classLoader + .getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml")); + configData = IOUtils.toString(classLoader + .getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -284,43 +311,50 @@ public class PolicyManagerServletTest extends Mockito{ ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity(); configurationEntity.setConfigBody(configData); configurationEntity.setConfigType("OTHER"); - configurationEntity.setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"); + configurationEntity + .setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"); configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } + } - @SuppressWarnings("static-access") - @Test - public void editBRMSRawPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + @SuppressWarnings("static-access") + @Test + public void editBRMSRawPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString( + classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml")); + configData = IOUtils.toString( + classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -332,39 +366,45 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editClosedLoopFaultPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editClosedLoopFaultPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString( + classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml")); + configData = IOUtils.toString(classLoader + .getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_Fault_TestClosedLoopPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -376,39 +416,45 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editClosedLoopPMPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editClosedLoopPMPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString( + classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml")); + configData = IOUtils.toString( + classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_PM_TestClosedLoopPMPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -420,46 +466,52 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_PM_TestClosedLoopPMPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_PM_TestClosedLoopPMPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editMicroServicePolicyTest(){ - GroupPolicyScopeList groupData = new GroupPolicyScopeList(); - groupData.setGroupName("Test"); - groupData.setGroupList("resource=SampleResource,service=SampleService,type=SampleType,closedLoopControlName=SampleClosedLoop"); - List<Object> groupListData = new ArrayList<>(); - groupListData.add(groupData); - commonClassDao = mock(CommonClassDao.class); - CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editMicroServicePolicyTest() { + GroupPolicyScopeList groupData = new GroupPolicyScopeList(); + groupData.setGroupName("Test"); + groupData.setGroupList("resource=SampleResource,service=SampleService,type=SampleType," + + "closedLoopControlName=SampleClosedLoop"); + List<Object> groupListData = new ArrayList<>(); + groupListData.add(groupData); + commonClassDao = mock(CommonClassDao.class); + CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = + IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml")); + configData = IOUtils + .toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_MS_vFirewall.1.xml"); entity.setPolicyData(policyContent); @@ -471,40 +523,48 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", "resource=SampleResource,service=SampleService,type=SampleType,closedLoopControlName=SampleClosedLoop")).thenReturn(groupListData); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", + "resource=SampleResource,service=SampleService,type=SampleType," + + "closedLoopControlName=SampleClosedLoop")) + .thenReturn(groupListData); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editFirewallPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editFirewallPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString( + classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml")); + configData = IOUtils.toString( + classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_FW_TestFireWallPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -516,39 +576,44 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Config_FW_TestFireWallPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_FW_TestFireWallPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editActionPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editActionPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; String configData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml")); - configData = IOUtils.toString(classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils + .toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml")); + configData = IOUtils.toString( + classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Action_TestActionPolicy.1.xml"); entity.setPolicyData(policyContent); @@ -558,141 +623,167 @@ public class PolicyManagerServletTest extends Mockito{ configurationEntity.setActionBodyName("com.Action_TestActionPolicy.1.json"); entity.setActionBodyEntity(configurationEntity); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @SuppressWarnings("static-access") - @Test - public void editDecisionPolicyTest(){ - List<Object> policyData = new ArrayList<>(); + } + + @SuppressWarnings("static-access") + @Test + public void editDecisionPolicyTest() { + List<Object> policyData = new ArrayList<>(); String policyContent = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader.getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyContent = IOUtils.toString(classLoader + .getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml"); entity.setPolicyData(policyContent); entity.setScope("com"); policyData.add(entity); - PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml', onlyFolders: false}}"); - for(int i =0; i < list.size(); i++){ - BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); + list.add( + "{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml'," + + " onlyFolders: false}}"); + for (int i = 0; i < list.size(); i++) { + BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { - when(request.getReader()).thenReturn(reader); - when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)).thenReturn(policyData); - servlet.setPolicyController(controller); - servlet.setTestUserId("Test"); - servlet.doPost(request, response); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(request.getReader()).thenReturn(reader); + when(controller.getRoles("Test")).thenReturn(rolesdata); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) + .thenReturn(policyData); + servlet.setPolicyController(controller); + servlet.setTestUserId("Test"); + servlet.doPost(request, response); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @Test - public void testAddScope(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + } + + @Test + public void testAddScope() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}"))); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}"))); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}"))); - for(int i=0; i<readers.size(); i++){ - try { - when(request.getReader()).thenReturn(readers.get(i)); - PolicyManagerServlet.setPolicyController(controller); - servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + readers.add(new BufferedReader( + new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}"))); + readers.add(new BufferedReader( + new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}"))); + readers.add(new BufferedReader(new StringReader( + "{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}"))); + for (int i = 0; i < readers.size(); i++) { + try { + when(request.getReader()).thenReturn(readers.get(i)); + PolicyManagerServlet.setPolicyController(controller); + servlet.doPost(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("success")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @Test - public void testClone(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + } + + @Test + public void testClone() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); - when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)).thenReturn(basePolicyData); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml', newPath: 'com.Config_testClone.1.xml'}}"))); - for(int i=0; i<readers.size(); i++){ - try { - when(request.getReader()).thenReturn(readers.get(i)); - PolicyManagerServlet.setPolicyController(controller); - servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", + "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", + null)).thenReturn(basePolicyData); + readers.add(new BufferedReader( + new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml'," + + " newPath: 'com.Config_testClone.1.xml'}}"))); + for (int i = 0; i < readers.size(); i++) { + try { + when(request.getReader()).thenReturn(readers.get(i)); + PolicyManagerServlet.setPolicyController(controller); + servlet.doPost(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("success")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @Test - public void testRename(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + } + + @Test + public void testRename() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); - when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); - when(controller.getDataByQuery("FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)).thenReturn(basePolicyData); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml', newPath: 'com.Config_testClone.1.xml'}}"))); - for(int i=0; i<readers.size(); i++){ - try { - when(request.getReader()).thenReturn(readers.get(i)); - PolicyManagerServlet.setPolicyController(controller); - servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", + "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); + when(controller.getDataByQuery( + "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", + null)).thenReturn(basePolicyData); + readers.add(new BufferedReader( + new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml'," + + " newPath: 'com.Config_testClone.1.xml'}}"))); + for (int i = 0; i < readers.size(); i++) { + try { + when(request.getReader()).thenReturn(readers.get(i)); + PolicyManagerServlet.setPolicyController(controller); + servlet.doPost(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("success")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } - - @Test - public void testRenameScope(){ - PolicyManagerServlet servlet = new PolicyManagerServlet(); + } + + @Test + public void testRenameScope() { + PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); - readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}"))); - for(int i=0; i<readers.size(); i++){ - try { - when(request.getReader()).thenReturn(readers.get(i)); - PolicyManagerServlet.setPolicyController(controller); - servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - fail(); - } + readers.add(new BufferedReader( + new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}"))); + for (int i = 0; i < readers.size(); i++) { + try { + when(request.getReader()).thenReturn(readers.get(i)); + PolicyManagerServlet.setPolicyController(controller); + servlet.doPost(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("success")); + } catch (Exception e1) { + logger.error("Exception Occured" + e1); + fail(); + } } - } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java index 2c56a8b7f..95296f4b0 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,10 +24,8 @@ package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; - import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.when; @@ -36,59 +36,60 @@ import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; public class PolicyNotificationMailTest { - private PolicyVersion version; - private String policyName = "com/Config_Test"; - private CommonClassDao commonClassDao; - private List<Object> data = null; - - @Before - public void setUp() throws Exception { - PolicyController.setjUnit(true); - PolicyController.setSmtpApplicationName("Test"); - PolicyController.setSmtpEmailExtension("test.com"); - PolicyController.setSmtpHost("test"); - PolicyController.setSmtpPort("23"); - PolicyController.setSmtpPassword("test"); - PolicyController.setSmtpUsername("test"); - - version = new PolicyVersion(); - version.setPolicyName("com/Config_Test"); - version.setModifiedBy("xyz"); - - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - watch.setPolicyName("com/Config_Test"); - data = new ArrayList<>(); - data.add(watch); - - commonClassDao = mock(CommonClassDao.class); - PolicyController.setCommonClassDao(commonClassDao); - when(commonClassDao.getDataByQuery("from WatchPolicyNotificationTable where policyName like:policyFileName", null)).thenReturn(data); - } + private PolicyVersion version; + private String policyName = "com/Config_Test"; + private CommonClassDao commonClassDao; + private List<Object> data = null; - @Test - public final void testJavaMailSenderImpl() { - PolicyNotificationMail notificationMail = new PolicyNotificationMail(); - try{ - assertTrue(notificationMail.javaMailSenderImpl() != null); - }catch(Exception e){ - fail(); - } - } + @Before + public void setUp() throws Exception { + PolicyController.setjUnit(true); + PolicyController.setSmtpApplicationName("Test"); + PolicyController.setSmtpEmailExtension("test.com"); + PolicyController.setSmtpHost("test"); + PolicyController.setSmtpPort("23"); + PolicyController.setSmtpPassword("test"); + PolicyController.setSmtpUsername("test"); + + version = new PolicyVersion(); + version.setPolicyName("com/Config_Test"); + version.setModifiedBy("xyz"); + + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName("com/Config_Test"); + data = new ArrayList<>(); + data.add(watch); + + commonClassDao = mock(CommonClassDao.class); + PolicyController.setCommonClassDao(commonClassDao); + when(commonClassDao.getDataByQuery( + "from WatchPolicyNotificationTable where policyName like:policyFileName", null)) + .thenReturn(data); + } - @Test - public final void testSendMail() { - PolicyNotificationMail notificationMail = new PolicyNotificationMail(); - try{ - notificationMail.sendMail(version, policyName, "EditPolicy", commonClassDao); - notificationMail.sendMail(version, policyName, "Rename", commonClassDao); - notificationMail.sendMail(version, policyName, "DeleteAll", commonClassDao); - notificationMail.sendMail(version, policyName, "DeleteOne", commonClassDao); - notificationMail.sendMail(version, policyName, "DeleteScope", commonClassDao); - notificationMail.sendMail(version, policyName, "SwitchVersion", commonClassDao); - notificationMail.sendMail(version, policyName, "Move", commonClassDao); - }catch(Exception e){ - fail(); - } - } + @Test + public final void testJavaMailSenderImpl() { + PolicyNotificationMail notificationMail = new PolicyNotificationMail(); + try { + assertTrue(notificationMail.javaMailSenderImpl() != null); + } catch (Exception e) { + fail(); + } + } + @Test + public final void testSendMail() { + PolicyNotificationMail notificationMail = new PolicyNotificationMail(); + try { + notificationMail.sendMail(version, policyName, "EditPolicy", commonClassDao); + notificationMail.sendMail(version, policyName, "Rename", commonClassDao); + notificationMail.sendMail(version, policyName, "DeleteAll", commonClassDao); + notificationMail.sendMail(version, policyName, "DeleteOne", commonClassDao); + notificationMail.sendMail(version, policyName, "DeleteScope", commonClassDao); + notificationMail.sendMail(version, policyName, "SwitchVersion", commonClassDao); + notificationMail.sendMail(version, policyName, "Move", commonClassDao); + } catch (Exception e) { + fail(); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java index 16cefd854..ce38f236f 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,16 +24,13 @@ package org.onap.policy.admin; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -51,182 +50,207 @@ import org.springframework.mock.web.MockHttpServletResponse; public class PolicyRestControllerTest { - private String clRequestString; - private String fwRequestString; - private String fwViewRequestString; - private HttpServletRequest request; - private MockHttpServletResponse response; - private static CommonClassDao commonClassDao; - private List<Object> prefixListData; - private List<Object> actionListData; - private List<Object> serviceListData; - private List<Object> addressGroupData; - private List<Object> securityZoneData; - private List<Object> serviceGroupData; - private List<Object> tagListData; - private List<Object> termListData; - - @Before - public void setUp() throws Exception { - commonClassDao = mock(CommonClassDao.class); - HttpSession mockSession = mock(HttpSession.class); - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - User user = new User(); - user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); - Mockito.when(request.getSession(false)).thenReturn(mockSession); - clRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," - + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\"," - + "\"version\":\"\",\"createdBy\":\"Demo\",\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," - + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\"," - + "\"version\":\"\",\"createdBy\":\"Demo\",\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:1439\"," - + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3]," - + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\",\"$$hashKey\":\"object:1526\"}," - + "{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}],\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\"," - + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\",\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\"," - + "\"trapCount2\":\"14\"}],\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"},{\"id\":\"Fault2\"," - + "\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\"," - + "\"notBox\":\"NOT\",\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\",\"connectTrap2\":\"Fault2\"," - + "\"trapCount2\":\"12\"}],\"jsonBodyData\":{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\"," - + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true,\"actions\":\"Test\",\"timeInterval\":\"11\"," - + "\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\",\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\"," - + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\",\"conditions\":\"SEND\"}," - + "\"policyName\":\"SampleTest\",\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," - + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\",\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\"," - + "\"verificationclearTimeOut\":\"13\"}},\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\"," - + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\"," - + "\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}," - + "{\"id\":\"A2\",\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":" - + "\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\",\"operatorBox\":\"OR\"," - + "\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\"," - + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1577\"," - + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":" - + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\",\"trigger2\":\"Test\"},{\"id\":\"A3" - + "\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\",\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}"; - - - fwRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[]," - + "\"type\":\"dir\",\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\",\"modifiedBy\":" - + "\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":" - + "\"dir\",\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\",\"modifiedBy\":\"Demo\"," - + "\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\",\"policy\":{\"policyType\":\"Config\",\"configPolicyType" - + "\":\"Firewall Config\",\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\",\"value\":\"Test\"}]," - + "\"fwattributes\":[],\"policyName\":\"SampleTest\",\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\"," - + "\"riskLevel\":\"1\",\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}}"; - - fwViewRequestString = "{\"policyData\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\",\"attributes\":[{\"id\":" - + "\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\",\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":" - + "\"SampleTest\",\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\",\"guard\":\"True\"," - + "\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}"; - - - - prefixListData = new ArrayList<>(); - PrefixList prefixList = new PrefixList(); - prefixList.setPrefixListName("Test"); - prefixList.setPrefixListValue("10.10.10.10/12"); - prefixListData.add(prefixList); - when(commonClassDao.getData(PrefixList.class)).thenReturn(prefixListData); - - actionListData = new ArrayList<>(); - ActionList actionList = new ActionList(); - actionList.setActionName("Test"); - actionListData.add(actionList); - when(commonClassDao.getData(ActionList.class)).thenReturn(actionListData); - - serviceListData = new ArrayList<>(); - ServiceList serviceList = new ServiceList(); - serviceList.setServiceName("Test"); - serviceList.setServiceType("SERVICE"); - serviceList.setServiceTransProtocol("Test"); - serviceList.setServiceAppProtocol("Test"); - serviceList.setServicePorts("8080"); - serviceListData.add(serviceList); - when(commonClassDao.getData(ServiceList.class)).thenReturn(serviceListData); - - addressGroupData = new ArrayList<>(); - AddressGroup addressGroup = new AddressGroup(); - addressGroup.setGroupName("Group_Test"); - addressGroup.setServiceList("Test"); - addressGroupData.add(addressGroup); - when(commonClassDao.getData(AddressGroup.class)).thenReturn(addressGroupData); - - securityZoneData = new ArrayList<>(); - SecurityZone securityZone = new SecurityZone(); - securityZone.setZoneName("Test"); - securityZone.setZoneValue("Test"); - securityZoneData.add(securityZone); - when(commonClassDao.getData(SecurityZone.class)).thenReturn(securityZoneData); - - serviceGroupData = new ArrayList<>(); - GroupServiceList serviceGroup = new GroupServiceList(); - serviceGroup.setGroupName("Group_Test"); - serviceGroup.setServiceList("Test"); - serviceGroupData.add(serviceGroup); - when(commonClassDao.getData(GroupServiceList.class)).thenReturn(serviceGroupData); - - tagListData = new ArrayList<>(); - FWTagPicker fwPicker = new FWTagPicker(); - fwPicker.setTagPickerName("Test"); - fwPicker.setTagValues("Test:8080"); - tagListData.add(fwPicker); - when(commonClassDao.getData(FWTagPicker.class)).thenReturn(tagListData); - - termListData = new ArrayList<>(); - TermList termList = new TermList(); - termList.setTermName("Test"); - termList.setFromZones("Test"); - termList.setToZones("Test"); - termList.setSrcIPList("Test"); - termList.setDestIPList("Test"); - termList.setSrcPortList("Test"); - termList.setDestPortList("Test"); - termList.setAction("Test"); - termListData.add(termList); - when(commonClassDao.getData(TermList.class)).thenReturn(termListData); - when(commonClassDao.getDataById(TermList.class, "termName", "Test")).thenReturn(termListData); - } - - @Test - public final void testPolicyCreationController() { - PolicyRestController controller = new PolicyRestController(); - BufferedReader reader = new BufferedReader(new StringReader(clRequestString)); - try { - Mockito.when(request.getReader()).thenReturn(reader); - controller.policyCreationController(request, response); - } catch (IOException e) { - fail(); - } - PolicyRestController controller1 = new PolicyRestController(); - CreateFirewallController.setCommonClassDao(commonClassDao); - BufferedReader reader1 = new BufferedReader(new StringReader(fwRequestString)); - try { - Mockito.when(request.getReader()).thenReturn(reader1); - controller1.policyCreationController(request, response); - } catch (IOException e) { - fail(); - } - - CreateFirewallController fwController = new CreateFirewallController(); - CreateFirewallController.setCommonClassDao(commonClassDao); - BufferedReader reader2 = new BufferedReader(new StringReader(fwViewRequestString)); - try { - Mockito.when(request.getReader()).thenReturn(reader2); - fwController.setFWViewRule(request, response); - } catch (IOException e) { - fail(); - } - } - - @Test - public final void testDeleteElasticData() { - PolicyRestController controller = new PolicyRestController(); - try { - controller.deleteElasticData("Test"); - } catch (Exception e) { - fail(); - } - } + private String clRequestString; + private String fwRequestString; + private String fwViewRequestString; + private HttpServletRequest request; + private MockHttpServletResponse response; + private static CommonClassDao commonClassDao; + private List<Object> prefixListData; + private List<Object> actionListData; + private List<Object> serviceListData; + private List<Object> addressGroupData; + private List<Object> securityZoneData; + private List<Object> serviceGroupData; + private List<Object> tagListData; + private List<Object> termListData; + + @Before + public void setUp() throws Exception { + commonClassDao = mock(CommonClassDao.class); + HttpSession mockSession = mock(HttpSession.class); + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + User user = new User(); + user.setOrgUserId("Test"); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) + .thenReturn(user); + Mockito.when(request.getSession(false)).thenReturn(mockSession); + clRequestString = + "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," + + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," + + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\"," + + "\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," + + "\"$$hashKey\":\"object:1439\",\"policy\":{\"policyType\":\"Config\"," + + "\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3]," + + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\"," + + "\"$$hashKey\":\"object:1526\"},{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}]," + + "\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\"," + + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\"," + + "\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\",\"trapCount2\":\"14\"}]," + + "\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"}," + + "{\"id\":\"Fault2\",\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":" + + "[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\",\"notBox\":\"NOT\"," + + "\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\"," + + "\"connectTrap2\":\"Fault2\",\"trapCount2\":\"12\"}],\"jsonBodyData\":" + + "{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\"," + + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true," + + "\"actions\":\"Test\",\"timeInterval\":\"11\",\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\"," + + "\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\"," + + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\"," + + "\"conditions\":\"SEND\"},\"policyName\":\"SampleTest\"," + + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," + + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\"," + + "\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\",\"verificationclearTimeOut\":\"13\"}}," + + "\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\"," + + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}]," + + "\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\"," + + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\"," + + "\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A3\"," + + "\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," + + "\"operatorBox\":\"OR\",\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\"," + + "\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\"," + + "\"$$hashKey\":\"object:1577\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":" + + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\"," + + "\"trigger2\":\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\"," + + "\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}"; + + + fwRequestString = + "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," + + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":" + + "{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\"," + + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\"," + + "\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\"," + + "\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":\"SampleTest\"," + + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," + + "\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\"," + + "\"securityZone\":\"Test\"}}}"; + + fwViewRequestString = + "{\"policyData\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\",\"attributes\":" + + "[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\",\"value\":\"Test\"}]," + + "\"fwattributes\":[],\"policyName\":\"SampleTest\",\"policyDescription\":\"SampleTest\"," + + "\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\",\"guard\":\"True\"," + + "\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}"; + + + + prefixListData = new ArrayList<>(); + PrefixList prefixList = new PrefixList(); + prefixList.setPrefixListName("Test"); + prefixList.setPrefixListValue("10.10.10.10/12"); + prefixListData.add(prefixList); + when(commonClassDao.getData(PrefixList.class)).thenReturn(prefixListData); + + actionListData = new ArrayList<>(); + ActionList actionList = new ActionList(); + actionList.setActionName("Test"); + actionListData.add(actionList); + when(commonClassDao.getData(ActionList.class)).thenReturn(actionListData); + + serviceListData = new ArrayList<>(); + ServiceList serviceList = new ServiceList(); + serviceList.setServiceName("Test"); + serviceList.setServiceType("SERVICE"); + serviceList.setServiceTransProtocol("Test"); + serviceList.setServiceAppProtocol("Test"); + serviceList.setServicePorts("8080"); + serviceListData.add(serviceList); + when(commonClassDao.getData(ServiceList.class)).thenReturn(serviceListData); + + addressGroupData = new ArrayList<>(); + AddressGroup addressGroup = new AddressGroup(); + addressGroup.setGroupName("Group_Test"); + addressGroup.setServiceList("Test"); + addressGroupData.add(addressGroup); + when(commonClassDao.getData(AddressGroup.class)).thenReturn(addressGroupData); + + securityZoneData = new ArrayList<>(); + SecurityZone securityZone = new SecurityZone(); + securityZone.setZoneName("Test"); + securityZone.setZoneValue("Test"); + securityZoneData.add(securityZone); + when(commonClassDao.getData(SecurityZone.class)).thenReturn(securityZoneData); + + serviceGroupData = new ArrayList<>(); + GroupServiceList serviceGroup = new GroupServiceList(); + serviceGroup.setGroupName("Group_Test"); + serviceGroup.setServiceList("Test"); + serviceGroupData.add(serviceGroup); + when(commonClassDao.getData(GroupServiceList.class)).thenReturn(serviceGroupData); + + tagListData = new ArrayList<>(); + FWTagPicker fwPicker = new FWTagPicker(); + fwPicker.setTagPickerName("Test"); + fwPicker.setTagValues("Test:8080"); + tagListData.add(fwPicker); + when(commonClassDao.getData(FWTagPicker.class)).thenReturn(tagListData); + + termListData = new ArrayList<>(); + TermList termList = new TermList(); + termList.setTermName("Test"); + termList.setFromZones("Test"); + termList.setToZones("Test"); + termList.setSrcIPList("Test"); + termList.setDestIPList("Test"); + termList.setSrcPortList("Test"); + termList.setDestPortList("Test"); + termList.setAction("Test"); + termListData.add(termList); + when(commonClassDao.getData(TermList.class)).thenReturn(termListData); + when(commonClassDao.getDataById(TermList.class, "termName", "Test")) + .thenReturn(termListData); + } + + @Test + public final void testPolicyCreationController() { + PolicyRestController controller = new PolicyRestController(); + BufferedReader reader = new BufferedReader(new StringReader(clRequestString)); + try { + Mockito.when(request.getReader()).thenReturn(reader); + controller.policyCreationController(request, response); + } catch (IOException e) { + fail(); + } + PolicyRestController controller1 = new PolicyRestController(); + CreateFirewallController.setCommonClassDao(commonClassDao); + BufferedReader reader1 = new BufferedReader(new StringReader(fwRequestString)); + try { + Mockito.when(request.getReader()).thenReturn(reader1); + controller1.policyCreationController(request, response); + } catch (IOException e) { + fail(); + } + + CreateFirewallController fwController = new CreateFirewallController(); + CreateFirewallController.setCommonClassDao(commonClassDao); + BufferedReader reader2 = new BufferedReader(new StringReader(fwViewRequestString)); + try { + Mockito.when(request.getReader()).thenReturn(reader2); + fwController.setFWViewRule(request, response); + } catch (IOException e) { + fail(); + } + } + @Test + public final void testDeleteElasticData() { + PolicyRestController controller = new PolicyRestController(); + try { + controller.deleteElasticData("Test"); + } catch (Exception e) { + fail(); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java index 7a3401568..d05b7933d 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,10 +24,8 @@ package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -35,30 +35,29 @@ import org.springframework.mock.web.MockHttpServletResponse; public class PolicyUserInfoControllerTest { - private HttpServletRequest request; - private MockHttpServletResponse response; - - @Before - public void setUp() throws Exception { - HttpSession mockSession = mock(HttpSession.class); - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - User user = new User(); - user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); - Mockito.when(request.getSession(false)).thenReturn(mockSession); - } - - @Test - public final void testGetPolicyUserInfo() { - PolicyUserInfoController controller = new PolicyUserInfoController(); - controller.getPolicyUserInfo(request, response); - try{ - assertTrue(response.getStatus() == 200); - }catch(Exception e){ - fail(); - } - - } - + private HttpServletRequest request; + private MockHttpServletResponse response; + + @Before + public void setUp() throws Exception { + HttpSession mockSession = mock(HttpSession.class); + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + User user = new User(); + user.setOrgUserId("Test"); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) + .thenReturn(user); + Mockito.when(request.getSession(false)).thenReturn(mockSession); + } + + @Test + public final void testGetPolicyUserInfo() { + PolicyUserInfoController controller = new PolicyUserInfoController(); + controller.getPolicyUserInfo(request, response); + try { + assertTrue(response.getStatus() == 200); + } catch (Exception e) { + fail(); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java index 55bdb313d..4b307f594 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -44,121 +46,120 @@ import com.att.research.xacml.api.pap.PDPPolicy; @RunWith(PowerMockRunner.class) @PrepareForTest({URL.class, RESTfulPAPEngine.class}) public class RESTfulPAPEngineTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private RESTfulPAPEngine engine = null; - private String name = "testName"; - private String id = "testID"; - private String description = "testDescription"; - private String policyType = "testType"; - private String policyContent = "testContent"; - private int jmxport = 0; - OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); - OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); - OnapPDP pdp = Mockito.mock(OnapPDP.class); - InputStream policy; - - @Before - public void runConstructor() throws Exception { - // Mock url and connection - URL url = PowerMockito.mock(URL.class); - PowerMockito.whenNew(URL.class).withArguments(Mockito.any()).thenReturn(url); - HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); - Mockito.when(url.openConnection()).thenReturn(connection); - Mockito.when(connection.getResponseCode()).thenReturn(HttpServletResponse.SC_NO_CONTENT); - - // Set the system property temporarily - String systemKey = "xacml.properties"; - String oldProperty = System.getProperty(systemKey); - System.setProperty(systemKey, "src/test/resources/xacml.admin.properties"); - - // Test constructor - String urlName = "localhost:1234"; - engine = new RESTfulPAPEngine(urlName); - - // Initialize policy - policy = new ByteArrayInputStream(policyContent.getBytes("UTF-8")); - - // Restore the original system property - if (oldProperty != null) { - System.setProperty(systemKey, oldProperty); - } - else { - System.clearProperty(systemKey); - } - } - - @Test - public void testGroups() throws Exception { - engine.setDefaultGroup(group); - assertEquals(engine.getDefaultGroup(), null); - engine.newGroup(name, description); - engine.removeGroup(group, newGroup ); - assertEquals(engine.getPDPGroup(pdp ), null); - assertEquals(engine.getPDPGroup(id), null); - assertEquals(engine.getPDP(id), null); - assertEquals(engine.getStatus(pdp), null); - - thrown.expect(NullPointerException.class); - engine.getOnapPDPGroups(); - fail("Expecting an exception."); - } - - @Test - public void testUpdateGroup() throws PAPException { - thrown.expect(PAPException.class); - engine.updateGroup(group); - fail("Expecting an exception."); - } - - @Test - public void testPDP() throws PAPException { - assertEquals(engine.getGroup(name), null); - engine.movePDP(pdp, newGroup); - - thrown.expect(PAPException.class); - engine.newPDP(id, newGroup, name, description, jmxport); - fail("Expecting an exception."); - } - - @Test - public void testUpdatePDP() throws PAPException { - thrown.expect(NullPointerException.class); - engine.updatePDP(pdp); - fail("Expecting an exception."); - } - - @Test - public void testRemovePDP() throws PAPException { - thrown.expect(NullPointerException.class); - engine.removePDP(pdp); - fail("Expecting an exception."); - } - - @Test - public void testValidatePolicy() throws PAPException { - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - - thrown.expect(PAPException.class); - engine.validatePolicyRequest(policyAdapter, policyType); - fail("Expecting an exception."); - } - - @Test - public void testPublishPolicy() throws PAPException { - thrown.expect(PAPException.class); - engine.publishPolicy(id, name, false, policy, newGroup); - fail("Expecting an exception."); - } - - @Test - public void testCopy() throws PAPException { - engine.copyFile(id, newGroup, policy); - PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class); - - thrown.expect(PAPException.class); - engine.copyPolicy(pdpPolicy , newGroup); - fail("Expecting an exception."); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private RESTfulPAPEngine engine = null; + private String name = "testName"; + private String id = "testID"; + private String description = "testDescription"; + private String policyType = "testType"; + private String policyContent = "testContent"; + private int jmxport = 0; + OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); + OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); + OnapPDP pdp = Mockito.mock(OnapPDP.class); + InputStream policy; + + @Before + public void runConstructor() throws Exception { + // Mock url and connection + URL url = PowerMockito.mock(URL.class); + PowerMockito.whenNew(URL.class).withArguments(Mockito.any()).thenReturn(url); + HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); + Mockito.when(url.openConnection()).thenReturn(connection); + Mockito.when(connection.getResponseCode()).thenReturn(HttpServletResponse.SC_NO_CONTENT); + + // Set the system property temporarily + String systemKey = "xacml.properties"; + String oldProperty = System.getProperty(systemKey); + System.setProperty(systemKey, "src/test/resources/xacml.admin.properties"); + + // Test constructor + String urlName = "localhost:1234"; + engine = new RESTfulPAPEngine(urlName); + + // Initialize policy + policy = new ByteArrayInputStream(policyContent.getBytes("UTF-8")); + + // Restore the original system property + if (oldProperty != null) { + System.setProperty(systemKey, oldProperty); + } else { + System.clearProperty(systemKey); + } + } + + @Test + public void testGroups() throws Exception { + engine.setDefaultGroup(group); + assertEquals(engine.getDefaultGroup(), null); + engine.newGroup(name, description); + engine.removeGroup(group, newGroup); + assertEquals(engine.getPDPGroup(pdp), null); + assertEquals(engine.getPDPGroup(id), null); + assertEquals(engine.getPDP(id), null); + assertEquals(engine.getStatus(pdp), null); + + thrown.expect(NullPointerException.class); + engine.getOnapPDPGroups(); + fail("Expecting an exception."); + } + + @Test + public void testUpdateGroup() throws PAPException { + thrown.expect(PAPException.class); + engine.updateGroup(group); + fail("Expecting an exception."); + } + + @Test + public void testPDP() throws PAPException { + assertEquals(engine.getGroup(name), null); + engine.movePDP(pdp, newGroup); + + thrown.expect(PAPException.class); + engine.newPDP(id, newGroup, name, description, jmxport); + fail("Expecting an exception."); + } + + @Test + public void testUpdatePDP() throws PAPException { + thrown.expect(NullPointerException.class); + engine.updatePDP(pdp); + fail("Expecting an exception."); + } + + @Test + public void testRemovePDP() throws PAPException { + thrown.expect(NullPointerException.class); + engine.removePDP(pdp); + fail("Expecting an exception."); + } + + @Test + public void testValidatePolicy() throws PAPException { + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + + thrown.expect(PAPException.class); + engine.validatePolicyRequest(policyAdapter, policyType); + fail("Expecting an exception."); + } + + @Test + public void testPublishPolicy() throws PAPException { + thrown.expect(PAPException.class); + engine.publishPolicy(id, name, false, policy, newGroup); + fail("Expecting an exception."); + } + + @Test + public void testCopy() throws PAPException { + engine.copyFile(id, newGroup, policy); + PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class); + + thrown.expect(PAPException.class); + engine.copyPolicy(pdpPolicy, newGroup); + fail("Expecting an exception."); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java index f211c6df0..dab2cba53 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,19 +30,19 @@ import org.mockito.Mockito; import org.onap.policy.controller.PolicyController; public class HibernateSessionTest { - @Before - public void setup() { - PolicyController.setLogdbUrl("testURL"); - PolicyController.setLogdbUserName("testUser"); - PolicyController.setLogdbPassword("testPass"); - PolicyController.setLogdbDialect("testDialect"); - PolicyController.setLogdbDriver("testDriver"); - } + @Before + public void setup() { + PolicyController.setLogdbUrl("testURL"); + PolicyController.setLogdbUserName("testUser"); + PolicyController.setLogdbPassword("testPass"); + PolicyController.setLogdbDialect("testDialect"); + PolicyController.setLogdbDriver("testDriver"); + } - @Test - public void testSession() { - SessionFactory factory = Mockito.mock(SessionFactory.class); - HibernateSession.setSession(factory); - assertNull(HibernateSession.getSession()); - } + @Test + public void testSession() { + SessionFactory factory = Mockito.mock(SessionFactory.class); + HibernateSession.setSession(factory); + assertNull(HibernateSession.getSession()); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java index 17ad56457..a4999ff42 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,16 +25,13 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -46,61 +45,63 @@ import org.springframework.mock.web.MockHttpServletResponse; public class AdminTabControllerTest { - private static Logger logger = FlexLogger.getLogger(AdminTabControllerTest.class); - private static CommonClassDao commonClassDao; - private HttpServletRequest request; - private MockHttpServletResponse response; - - @Before - public void setUp() throws Exception { + private static Logger logger = FlexLogger.getLogger(AdminTabControllerTest.class); + private static CommonClassDao commonClassDao; + private HttpServletRequest request; + private MockHttpServletResponse response; + + @Before + public void setUp() throws Exception { - logger.info("setUp: Entering"); + logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); - - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - - HttpSession mockSession = mock(HttpSession.class); - User user = new User(); - user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); - Mockito.when(request.getSession(false)).thenReturn(mockSession); - - AdminTabController.setCommonClassDao(commonClassDao); - + + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + + HttpSession mockSession = mock(HttpSession.class); + User user = new User(); + user.setOrgUserId("Test"); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) + .thenReturn(user); + Mockito.when(request.getSession(false)).thenReturn(mockSession); + + AdminTabController.setCommonClassDao(commonClassDao); + GlobalRoleSettings globalRole = new GlobalRoleSettings(); globalRole.setLockdown(true); globalRole.setRole("super-admin"); List<Object> globalRoles = new ArrayList<>(); globalRoles.add(globalRole); when(commonClassDao.getData(GlobalRoleSettings.class)).thenReturn(globalRoles); - } - - @Test - public void testGetAdminRole(){ - AdminTabController admin = new AdminTabController(); - try { - admin.getAdminTabEntityData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } - - @Test - public void testSaveAdminRole() throws Exception{ - AdminTabController admin = new AdminTabController(); - String data = "{\"lockdowndata\":{\"lockdown\":true}}"; - BufferedReader reader = new BufferedReader(new StringReader(data)); - try { - when(request.getReader()).thenReturn(reader); - admin.saveAdminTabLockdownValue(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } - + } + + @Test + public void testGetAdminRole() { + AdminTabController admin = new AdminTabController(); + try { + admin.getAdminTabEntityData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("lockdowndata")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } + + @Test + public void testSaveAdminRole() throws Exception { + AdminTabController admin = new AdminTabController(); + String data = "{\"lockdowndata\":{\"lockdown\":true}}"; + BufferedReader reader = new BufferedReader(new StringReader(data)); + try { + when(request.getReader()).thenReturn(reader); + admin.saveAdminTabLockdownValue(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java index 95fa962a0..5dd5d7ee3 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,70 +40,70 @@ import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) public class AutoPushControllerTest { - private PolicyController controller = new PolicyController();; - private AutoPushController apController = new AutoPushController(); + private PolicyController controller = new PolicyController();; + private AutoPushController apController = new AutoPushController(); - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Test - public void testAutoPushSetGet() throws IOException { - // Get and set tests - apController.setPolicyController(controller); - assertEquals(apController.getPolicyController(), controller); - } + @Test + public void testAutoPushSetGet() throws IOException { + // Get and set tests + apController.setPolicyController(controller); + assertEquals(apController.getPolicyController(), controller); + } - @Test - public void testNegativeCase1() { - try { - apController.getPolicyGroupContainerData(null, null); - } catch (Exception ex) { - fail("No exceptions expected, received: " + ex); + @Test + public void testNegativeCase1() { + try { + apController.getPolicyGroupContainerData(null, null); + } catch (Exception ex) { + fail("No exceptions expected, received: " + ex); + } } - } - @Test - public void testNegativeCase2() throws IOException { - thrown.expect(NullPointerException.class); - apController.pushPolicyToPDPGroup(null, null); - } + @Test + public void testNegativeCase2() throws IOException { + thrown.expect(NullPointerException.class); + apController.pushPolicyToPDPGroup(null, null); + } - @Test - public void testNegativeCase3() throws IOException { - thrown.expect(NullPointerException.class); - apController.removePDPGroup(null, null); - } + @Test + public void testNegativeCase3() throws IOException { + thrown.expect(NullPointerException.class); + apController.removePDPGroup(null, null); + } - @Test(expected = NullPointerException.class) - public void testRefresh() throws IOException { - apController.refreshGroups(); - } + @Test(expected = NullPointerException.class) + public void testRefresh() throws IOException { + apController.refreshGroups(); + } - @PrepareForTest({UserUtils.class}) - @Test - public void testRequests() throws Exception { - // Mock user utilities - PowerMockito.mockStatic(UserUtils.class); - User user = new User(); - Mockito.when(UserUtils.getUserSession(Mockito.any())).thenReturn(user); + @PrepareForTest({UserUtils.class}) + @Test + public void testRequests() throws Exception { + // Mock user utilities + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + Mockito.when(UserUtils.getUserSession(Mockito.any())).thenReturn(user); - // Mock policy controller - PolicyController pController = Mockito.mock(PolicyController.class); - PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(pController); - Mockito.when(pController.getRoles(Mockito.any())).thenReturn(null); + // Mock policy controller + PolicyController pController = Mockito.mock(PolicyController.class); + PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(pController); + Mockito.when(pController.getRoles(Mockito.any())).thenReturn(null); - // Test group container - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - apController.getPolicyGroupContainerData(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + // Test group container + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + apController.getPolicyGroupContainerData(request, response); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - // Test push - apController.pushPolicyToPDPGroup(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + // Test push + apController.pushPolicyToPDPGroup(request, response); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - // Test remove - apController.removePDPGroup(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - } + // Test remove + apController.removePDPGroup(request, response); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java index 1301d3f3d..ea67bbd34 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +31,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -41,11 +42,9 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; - import org.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -57,12 +56,10 @@ import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.PolicyEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jackson.JsonLoader; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -72,481 +69,496 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; /** - * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests - * for the class {@link <code>CreateDcaeMicroServiceController</code>}* - * - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. + * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests for the class + * {@link <code>CreateDcaeMicroServiceController</code>}* * + * All JUnits are designed to run in the local development environment where they have write + * privileges and can execute time-sensitive tasks. * - * */ public class CreateDcaeMicroServiceControllerTest { - - private static Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceControllerTest.class); - private static CommonClassDao commonClassDao; - private String jsonString = null; - private String configBodyString = null; - private HttpServletRequest request = null; - - @Before - public void setUp() throws Exception { - - logger.info("setUp: Entering"); + + private static Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceControllerTest.class); + private static CommonClassDao commonClassDao; + private String jsonString = null; + private String configBodyString = null; + private HttpServletRequest request = null; + + @Before + public void setUp() throws Exception { + + logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); List<Object> microServiceModelsData = new ArrayList<Object>(); MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("OpenOnap-Junit"); + testData.setVersion("OpenOnap-Junit"); microServiceModelsData.add(testData); // mock the getDataById() call - when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test")).thenReturn(microServiceModelsData); - - jsonString = "{\"policyData\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - - configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," - + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\"," - + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}"; - - request = mock(HttpServletRequest.class); + when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test")) + .thenReturn(microServiceModelsData); + + jsonString = + "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," + + "\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\",\"createdBy\": \"someone\"," + + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\", \"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + + configBodyString = + "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\"," + + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\"," + + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\"," + + "\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\",\"name\":\"test\"," + + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\"," + + "\"target\":\"SNIRO\"}}"; + + request = mock(HttpServletRequest.class); BufferedReader br = new BufferedReader(new StringReader(jsonString)); // mock the getReader() call - when(request.getReader()).thenReturn(br); - + when(request.getReader()).thenReturn(br); + logger.info("setUp: exit"); - } - - - /** - * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, - * JsonNode) method test - */ - - @Test - public void testSetDataToPolicyRestAdapter() { - - logger.debug("testSetDataToPolicyRestAdapter: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); - - JsonNode root = null; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter policyData = null; - try { - root = JsonLoader.fromString(jsonString); - policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - } catch (Exception e) { - logger.error("testSetDataToPolicyRestAdapter", e); - } - - PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root); - assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); - - logger.debug("result.getJsonBody() : " + result.getJsonBody()); - logger.debug("testSetDataToPolicyRestAdapter: exit"); - } - - /** - * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest, - * HttpServletResponse) method test - */ - - @Test - public void testGetDCAEMSTemplateData() { - - logger.debug("testGetDCAEMSTemplateData: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}"; - try { - - CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - // mock the getReader() call - when(request.getReader()).thenReturn(br); - - List<Object> microServiceModelsData = new ArrayList<Object>(); - MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("1707.4.1.2-Junit"); - microServiceModelsData.add(testData); - // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData); - - controller.getDCAEMSTemplateData(request, response); - - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData")); - - logger.debug("response: " + response.getContentAsString()); - - } catch (Exception e) { - logger.error("testGetDCAEMSTemplateData", e); - } - - logger.debug("testGetDCAEMSTemplateData: exit"); - } - - /** - * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, - * HttpServletResponse) method test - */ - - @Test - public void testGetModelServiceVersionData() { - - logger.debug("testGetModelServiceVersionData: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}"; - try { - - CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - // mock the getReader() call - when(request.getReader()).thenReturn(br); - - List<Object> microServiceModelsData = new ArrayList<Object>(); - MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("1707.4.1.2-Junit"); - microServiceModelsData.add(testData); - - // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData); - controller.getModelServiceVersionData(request, response); - - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit")); - - logger.debug("response: " + response.getContentAsString()); - - } catch (Exception e) { - logger.error("testGetModelServiceVersionData", e); - fail("testGetModelServiceVersionData failed due to: " + e); - } - - logger.debug("testGetModelServiceVersionData: exit"); - } - - /** - * Run the void getDCAEPriorityValuesData(HttpServletRequest, - * HttpServletResponse) method test - */ - - @Test - public void testGetDCAEPriorityValuesData() { - - logger.debug("testGetDCAEPriorityValuesData: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - try{ - controller.getDCAEPriorityValuesData(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas")); - logger.debug("response: " + response.getContentAsString()); + } + + /** + * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test + */ + + @Test + public void testSetDataToPolicyRestAdapter() { + + logger.debug("testSetDataToPolicyRestAdapter: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); + + JsonNode root = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter policyData = null; + try { + root = JsonLoader.fromString(jsonString); + policyData = (PolicyRestAdapter) mapper.readValue( + root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); } catch (Exception e) { - logger.error("testGetDCAEPriorityValuesData", e); - fail("testGetDCAEPriorityValuesData failed due to: " + e); - } - - logger.debug("testGetDCAEPriorityValuesData: exit"); - } - - /** - * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, - * PolicyEntity) method test - */ - - @Test - public void testPrePopulateDCAEMSPolicyData() { - - logger.debug("testPrePopulateDCAEMSPolicyData: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - - // populate an entity object for testing - PolicyEntity entity = new PolicyEntity(); - ConfigurationDataEntity configData = new ConfigurationDataEntity(); - configData.setConfigBody(configBodyString); - entity.setConfigurationData(configData); - - JsonNode root = null; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter restAdapter = null; - - try { - root = JsonLoader.fromString(jsonString); - restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - PolicyType policyType = new PolicyType(); - TargetType target = new TargetType(); - - // create guard attribute - AnyOfType anyOfType = new AnyOfType(); - AllOfType alltype = new AllOfType(); - MatchType matchType = new MatchType(); - // set value - AttributeValueType attributeValue1 = new AttributeValueType(); - attributeValue1.getContent().add("True"); - matchType.setAttributeValue(attributeValue1); + logger.error("testSetDataToPolicyRestAdapter", e); + } + + PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root); + assertTrue( + result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); + + logger.debug("result.getJsonBody() : " + result.getJsonBody()); + logger.debug("testSetDataToPolicyRestAdapter: exit"); + } + + /** + * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest, HttpServletResponse) method + * test + */ + + @Test + public void testGetDCAEMSTemplateData() { + + logger.debug("testGetDCAEMSTemplateData: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}"; + try { + + CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + // mock the getReader() call + when(request.getReader()).thenReturn(br); + + List<Object> microServiceModelsData = new ArrayList<Object>(); + MicroServiceModels testData = new MicroServiceModels(); + testData.setVersion("1707.4.1.2-Junit"); + microServiceModelsData.add(testData); + // mock the getDataById() call with the same MS model name + when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", + "DkatPolicyBody")).thenReturn(microServiceModelsData); + + controller.getDCAEMSTemplateData(request, response); + + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("dcaeModelData")); + + logger.debug("response: " + response.getContentAsString()); + + } catch (Exception e) { + logger.error("testGetDCAEMSTemplateData", e); + } + + logger.debug("testGetDCAEMSTemplateData: exit"); + } + + /** + * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse) + * method test + */ + + @Test + public void testGetModelServiceVersionData() { + + logger.debug("testGetModelServiceVersionData: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}"; + try { + + CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao); + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + // mock the getReader() call + when(request.getReader()).thenReturn(br); + + List<Object> microServiceModelsData = new ArrayList<Object>(); + MicroServiceModels testData = new MicroServiceModels(); + testData.setVersion("1707.4.1.2-Junit"); + microServiceModelsData.add(testData); + + // mock the getDataById() call with the same MS model name + when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", + "DkatPolicyBody")).thenReturn(microServiceModelsData); + controller.getModelServiceVersionData(request, response); + + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("1707.4.1.2-Junit")); + + logger.debug("response: " + response.getContentAsString()); + + } catch (Exception e) { + logger.error("testGetModelServiceVersionData", e); + fail("testGetModelServiceVersionData failed due to: " + e); + } + + logger.debug("testGetModelServiceVersionData: exit"); + } + + /** + * Run the void getDCAEPriorityValuesData(HttpServletRequest, HttpServletResponse) method test + */ + + @Test + public void testGetDCAEPriorityValuesData() { + + logger.debug("testGetDCAEPriorityValuesData: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + try { + controller.getDCAEPriorityValuesData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("priorityDatas")); + logger.debug("response: " + response.getContentAsString()); + } catch (Exception e) { + logger.error("testGetDCAEPriorityValuesData", e); + fail("testGetDCAEPriorityValuesData failed due to: " + e); + } + + logger.debug("testGetDCAEPriorityValuesData: exit"); + } + + /** + * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test + */ + + @Test + public void testPrePopulateDCAEMSPolicyData() { + + logger.debug("testPrePopulateDCAEMSPolicyData: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + + // populate an entity object for testing + PolicyEntity entity = new PolicyEntity(); + ConfigurationDataEntity configData = new ConfigurationDataEntity(); + configData.setConfigBody(configBodyString); + entity.setConfigurationData(configData); + + JsonNode root = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter restAdapter = null; + + try { + root = JsonLoader.fromString(jsonString); + restAdapter = (PolicyRestAdapter) mapper.readValue( + root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + PolicyType policyType = new PolicyType(); + TargetType target = new TargetType(); + + // create guard attribute + AnyOfType anyOfType = new AnyOfType(); + AllOfType alltype = new AllOfType(); + MatchType matchType = new MatchType(); + // set value + AttributeValueType attributeValue1 = new AttributeValueType(); + attributeValue1.getContent().add("True"); + matchType.setAttributeValue(attributeValue1); // set Id - AttributeDesignatorType designator = new AttributeDesignatorType(); - designator.setAttributeId("guard"); - matchType.setAttributeDesignator(designator); - alltype.getMatch().add(matchType); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy = new MatchType(); - // set value - AttributeValueType dummyValue = new AttributeValueType(); - dummyValue.getContent().add("dummy"); - matchDummy.setAttributeValue(dummyValue); + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId("guard"); + matchType.setAttributeDesignator(designator); + alltype.getMatch().add(matchType); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy = new MatchType(); + // set value + AttributeValueType dummyValue = new AttributeValueType(); + dummyValue.getContent().add("dummy"); + matchDummy.setAttributeValue(dummyValue); // set Id - AttributeDesignatorType designatorDummy = new AttributeDesignatorType(); - designatorDummy.setAttributeId("dummyId"); - matchDummy.setAttributeDesignator(designatorDummy); - - alltype.getMatch().add(matchDummy); - anyOfType.getAllOf().add(alltype); - - target.getAnyOf().add(anyOfType); - - // create RiskType attribute - AnyOfType anyRiskType = new AnyOfType(); - AllOfType allRiskType = new AllOfType(); - MatchType matchRiskType = new MatchType(); - // set value - AttributeValueType riskTypeValue = new AttributeValueType(); - riskTypeValue.getContent().add("test"); - matchRiskType.setAttributeValue(riskTypeValue); + AttributeDesignatorType designatorDummy = new AttributeDesignatorType(); + designatorDummy.setAttributeId("dummyId"); + matchDummy.setAttributeDesignator(designatorDummy); + + alltype.getMatch().add(matchDummy); + anyOfType.getAllOf().add(alltype); + + target.getAnyOf().add(anyOfType); + + // create RiskType attribute + AnyOfType anyRiskType = new AnyOfType(); + AllOfType allRiskType = new AllOfType(); + MatchType matchRiskType = new MatchType(); + // set value + AttributeValueType riskTypeValue = new AttributeValueType(); + riskTypeValue.getContent().add("test"); + matchRiskType.setAttributeValue(riskTypeValue); // set Id - AttributeDesignatorType designatorRiskType = new AttributeDesignatorType(); - designatorRiskType.setAttributeId("RiskType"); - matchRiskType.setAttributeDesignator(designatorRiskType); - allRiskType.getMatch().add(matchRiskType); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy1 = new MatchType(); - // set value - AttributeValueType dummy1Value = new AttributeValueType(); - dummy1Value.getContent().add("dummy"); - matchDummy1.setAttributeValue(dummy1Value); + AttributeDesignatorType designatorRiskType = new AttributeDesignatorType(); + designatorRiskType.setAttributeId("RiskType"); + matchRiskType.setAttributeDesignator(designatorRiskType); + allRiskType.getMatch().add(matchRiskType); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy1 = new MatchType(); + // set value + AttributeValueType dummy1Value = new AttributeValueType(); + dummy1Value.getContent().add("dummy"); + matchDummy1.setAttributeValue(dummy1Value); // set Id - AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType(); - designatorDummy1.setAttributeId("dummyId"); - matchDummy1.setAttributeDesignator(designatorDummy1); - - allRiskType.getMatch().add(matchDummy1); - - anyRiskType.getAllOf().add(allRiskType); - - target.getAnyOf().add(anyRiskType); - - // create RiskLevel attribute - AnyOfType anyRiskLevel = new AnyOfType(); - AllOfType allRiskLevel = new AllOfType(); - MatchType matchRiskLevel = new MatchType(); - // set value - AttributeValueType riskLevel = new AttributeValueType(); - riskLevel.getContent().add("3"); - matchRiskLevel.setAttributeValue(riskLevel); + AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType(); + designatorDummy1.setAttributeId("dummyId"); + matchDummy1.setAttributeDesignator(designatorDummy1); + + allRiskType.getMatch().add(matchDummy1); + + anyRiskType.getAllOf().add(allRiskType); + + target.getAnyOf().add(anyRiskType); + + // create RiskLevel attribute + AnyOfType anyRiskLevel = new AnyOfType(); + AllOfType allRiskLevel = new AllOfType(); + MatchType matchRiskLevel = new MatchType(); + // set value + AttributeValueType riskLevel = new AttributeValueType(); + riskLevel.getContent().add("3"); + matchRiskLevel.setAttributeValue(riskLevel); // set Id - AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType(); - designatorRiskLevel.setAttributeId("RiskLevel"); - matchRiskLevel.setAttributeDesignator(designatorRiskLevel); - allRiskLevel.getMatch().add(matchRiskLevel); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy2 = new MatchType(); - // set value - AttributeValueType dummy2Value = new AttributeValueType(); - dummy2Value.getContent().add("dummy"); - matchDummy2.setAttributeValue(dummy2Value); + AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType(); + designatorRiskLevel.setAttributeId("RiskLevel"); + matchRiskLevel.setAttributeDesignator(designatorRiskLevel); + allRiskLevel.getMatch().add(matchRiskLevel); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy2 = new MatchType(); + // set value + AttributeValueType dummy2Value = new AttributeValueType(); + dummy2Value.getContent().add("dummy"); + matchDummy2.setAttributeValue(dummy2Value); // set Id - AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType(); - designatorDummy2.setAttributeId("dummyId"); - matchDummy2.setAttributeDesignator(designatorDummy2); - - allRiskLevel.getMatch().add(matchDummy2); - - anyRiskLevel.getAllOf().add(allRiskLevel); - target.getAnyOf().add(anyRiskLevel); - - policyType.setTarget(target); - - restAdapter.setPolicyData(policyType); - - controller.prePopulateDCAEMSPolicyData(restAdapter, entity); - - logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType()); - logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel()); - logger.error("restAdapter.getGuard() : " + restAdapter.getGuard()); - - assertEquals("True", restAdapter.getGuard()); - assertEquals("3", restAdapter.getRiskLevel()); - assertEquals("test", restAdapter.getRiskType()); - - } catch (Exception e) { - logger.error("testPrePopulateDCAEMSPolicyData", e); - fail("testPrePopulateDCAEMSPolicyData failed due to: " + e); - } - - logger.debug("testPrePopulateDCAEMSPolicyData: exit"); - - } - - /** - * Run the Map<String,String> convert(String, String) method test - */ - - @Test - public void testConvert(){ - logger.debug("testConvert: enter"); - - String str = "k1=v1,k2=v2,k3=v3"; - String split = ","; - Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split); - assertTrue(result != null && result.size() == 3); - - logger.debug("testConvert: exit"); - } - - /** - * Run the Map<String,String> convertMap(Map<String,String>, - * Map<String,String>) method test - */ - - @Test - public void testConvertMap(){ - logger.debug("testConvertMap: enter"); - - CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); - Map<String,String> attributesMap = new HashMap<String, String>(); - Map<String,String> attributesRefMap = new HashMap<String, String>(); - Map<String,String> attributesListRefMap = controller.getAttributesListRefMap(); - Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList(); - LinkedList<String> list = new LinkedList<String>(); - - attributesMap.put("keyOne", "valueOne"); - attributesMap.put("keyTwo", "valueTwo"); - attributesMap.put("keyThree", "valueThree"); - - attributesRefMap.put("key4", "value4"); - attributesRefMap.put("key5", "value5"); - attributesRefMap.put("key6", "value6"); - - attributesListRefMap.put("key7", "value7"); - - list.add("l1"); - list.add("l2"); - arrayTextList.put("key8", list); - - Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap); - - assertTrue(result != null && result.size() == 8); - - assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]")); - - logger.debug("testConvertMap: exit"); - } - - /** - * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) - * method test - */ - - //@Ignore - @Test - public void testSetMSModelData() { - - logger.debug("testSetMSModelData: enter"); - - HttpServletRequest request = createMock(HttpServletRequest.class); - expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p"); - expect(request.getMethod()).andReturn("post"); - expect(request.getHeader("Content-length")).andReturn("7809"); - - expect(request.getContentLength()).andReturn(7809); - - try { - // value of fileName needs to be matched to your local directory - String fileName = ""; - try { - ClassLoader classLoader = getClass().getClassLoader(); - fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath(); - } catch (Exception e1) { - logger.error("Exception Occured while loading file"+e1); - } - expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName)); - expect(request.getCharacterEncoding()).andReturn("UTF-8"); - expect(request.getContentLength()).andReturn(1024); - replay(request); - - } catch (Exception e) { - logger.error("testSetMSModelData" + e); - e.printStackTrace(); - } - - logger.debug("testSetMSModelData: exit"); - } - - /** - * - * @ Get File Stream - * - */ - private class MockServletInputStream extends ServletInputStream { - - InputStream fis = null; - public MockServletInputStream(String fileName) { - try { - fis = new FileInputStream(fileName); - } catch (Exception genExe) { - genExe.printStackTrace(); - } - } - @Override - public int read() throws IOException { - if(fis.available() > 0) { - return fis.read(); - } - return 0; - } - - @Override - public int read(byte[] bytes, int len, int size) throws IOException { - if(fis.available() > 0) { - int length = fis.read(bytes, len, size); - return length; - } - return -1; - } - @Override - public boolean isFinished() { - return false; - } - @Override - public boolean isReady() { - return false; - } - @Override - public void setReadListener(ReadListener arg0) { - - } - } - -}
\ No newline at end of file + AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType(); + designatorDummy2.setAttributeId("dummyId"); + matchDummy2.setAttributeDesignator(designatorDummy2); + + allRiskLevel.getMatch().add(matchDummy2); + + anyRiskLevel.getAllOf().add(allRiskLevel); + target.getAnyOf().add(anyRiskLevel); + + policyType.setTarget(target); + + restAdapter.setPolicyData(policyType); + + controller.prePopulateDCAEMSPolicyData(restAdapter, entity); + + logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType()); + logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel()); + logger.error("restAdapter.getGuard() : " + restAdapter.getGuard()); + + assertEquals("True", restAdapter.getGuard()); + assertEquals("3", restAdapter.getRiskLevel()); + assertEquals("test", restAdapter.getRiskType()); + + } catch (Exception e) { + logger.error("testPrePopulateDCAEMSPolicyData", e); + fail("testPrePopulateDCAEMSPolicyData failed due to: " + e); + } + + logger.debug("testPrePopulateDCAEMSPolicyData: exit"); + + } + + /** + * Run the Map<String,String> convert(String, String) method test + */ + + @Test + public void testConvert() { + logger.debug("testConvert: enter"); + + String str = "k1=v1,k2=v2,k3=v3"; + String split = ","; + Map<String, String> result = CreateDcaeMicroServiceController.convert(str, split); + assertTrue(result != null && result.size() == 3); + + logger.debug("testConvert: exit"); + } + + /** + * Run the Map<String,String> convertMap(Map<String,String>, Map<String,String>) method test + */ + + @Test + public void testConvertMap() { + logger.debug("testConvertMap: enter"); + + CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController(); + Map<String, String> attributesMap = new HashMap<String, String>(); + Map<String, String> attributesRefMap = new HashMap<String, String>(); + Map<String, String> attributesListRefMap = controller.getAttributesListRefMap(); + Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList(); + LinkedList<String> list = new LinkedList<String>(); + + attributesMap.put("keyOne", "valueOne"); + attributesMap.put("keyTwo", "valueTwo"); + attributesMap.put("keyThree", "valueThree"); + + attributesRefMap.put("key4", "value4"); + attributesRefMap.put("key5", "value5"); + attributesRefMap.put("key6", "value6"); + + attributesListRefMap.put("key7", "value7"); + + list.add("l1"); + list.add("l2"); + arrayTextList.put("key8", list); + + Map<String, String> result = controller.convertMap(attributesMap, attributesRefMap); + + assertTrue(result != null && result.size() == 8); + + assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]")); + + logger.debug("testConvertMap: exit"); + } + + /** + * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test + */ + + // @Ignore + @Test + public void testSetMSModelData() { + + logger.debug("testSetMSModelData: enter"); + + HttpServletRequest request = createMock(HttpServletRequest.class); + expect(request.getContentType()) + .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p"); + expect(request.getMethod()).andReturn("post"); + expect(request.getHeader("Content-length")).andReturn("7809"); + + expect(request.getContentLength()).andReturn(7809); + + try { + // value of fileName needs to be matched to your local directory + String fileName = ""; + try { + ClassLoader classLoader = getClass().getClassLoader(); + fileName = + new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()) + .getAbsolutePath(); + } catch (Exception e1) { + logger.error("Exception Occured while loading file" + e1); + } + expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName)); + expect(request.getCharacterEncoding()).andReturn("UTF-8"); + expect(request.getContentLength()).andReturn(1024); + replay(request); + + } catch (Exception e) { + logger.error("testSetMSModelData" + e); + e.printStackTrace(); + } + + logger.debug("testSetMSModelData: exit"); + } + + /** + * + * @ Get File Stream + * + */ + private class MockServletInputStream extends ServletInputStream { + + InputStream fis = null; + + public MockServletInputStream(String fileName) { + try { + fis = new FileInputStream(fileName); + } catch (Exception genExe) { + genExe.printStackTrace(); + } + } + + @Override + public int read() throws IOException { + if (fis.available() > 0) { + return fis.read(); + } + return 0; + } + + @Override + public int read(byte[] bytes, int len, int size) throws IOException { + if (fis.available() > 0) { + int length = fis.read(bytes, len, size); + return length; + } + return -1; + } + + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener arg0) { + + } + } +} diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java index 35395a859..6747e9669 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +31,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -38,11 +39,9 @@ import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; - import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; - import org.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -54,12 +53,10 @@ import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.PolicyEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jackson.JsonLoader; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -69,400 +66,416 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; /** - * The class <code>CreateOptimizationControllerTest</code> contains tests - * for the class {@link <code>CreateOptimizationController</code>}* + * The class <code>CreateOptimizationControllerTest</code> contains tests for the class + * {@link <code>CreateOptimizationController</code>}* * - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. + * All JUnits are designed to run in the local development environment where they have write + * privileges and can execute time-sensitive tasks. */ public class CreateOptimizationControllerTest { - - private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class); - private static CommonClassDao commonClassDao; - private String jsonString = null; - private String configBodyString = null; - private HttpServletRequest request = null; - - @Before - public void setUp() throws Exception { - - logger.info("setUp: Entering"); + + private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class); + private static CommonClassDao commonClassDao; + private String jsonString = null; + private String configBodyString = null; + private HttpServletRequest request = null; + + @Before + public void setUp() throws Exception { + + logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); List<Object> optimizationModelsData = new ArrayList<Object>(); OptimizationModels testData = new OptimizationModels(); - testData.setVersion("OpenOnap-Junit"); + testData.setVersion("OpenOnap-Junit"); optimizationModelsData.add(testData); // mock the getDataById() call - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test")).thenReturn(optimizationModelsData); - - jsonString = "{\"policyData\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\",\"policyName\": \"testPolicy\", " - + " \"policyDescription\": \"testing input\", \"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - - configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," - + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\"," - + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"TEST\"}}"; - - request = mock(HttpServletRequest.class); + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test")) + .thenReturn(optimizationModelsData); + + jsonString = + "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," + + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," + + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\"," + + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + + configBodyString = + "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\"," + + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\"," + + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\"," + + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\"," + + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\"," + + "\"target\":\"TEST\"}}"; + + request = mock(HttpServletRequest.class); BufferedReader br = new BufferedReader(new StringReader(jsonString)); // mock the getReader() call - when(request.getReader()).thenReturn(br); - + when(request.getReader()).thenReturn(br); + logger.info("setUp: exit"); - } - - - /** - * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, - * JsonNode) method test - */ - - @Test - public void testSetDataToPolicyRestAdapter() { - - logger.debug("testSetDataToPolicyRestAdapter: enter"); - - CreateOptimizationController controller = new CreateOptimizationController(); - CreateOptimizationController.setCommonClassDao(commonClassDao); - - JsonNode root = null; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter policyData = null; - try { - root = JsonLoader.fromString(jsonString); - policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - } catch (Exception e) { - logger.error("testSetDataToPolicyRestAdapter", e); - } - - PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root); - assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); - - logger.debug("result.getJsonBody() : " + result.getJsonBody()); - logger.debug("testSetDataToPolicyRestAdapter: exit"); - } - - - /** - * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, - * HttpServletResponse) method test - */ - - @Test - public void testGetOptimizationTemplateData() { - - logger.debug("testGetOptimizationTemplateData: enter"); - - CreateOptimizationController controller = new CreateOptimizationController(); - MockHttpServletResponse response = new MockHttpServletResponse(); - String modelJson = "{\"policyData\":\"testPolicyBody\"}"; - try { - - CreateOptimizationController.setCommonClassDao(commonClassDao); - - BufferedReader br = new BufferedReader(new StringReader(modelJson)); - // mock the getReader() call - when(request.getReader()).thenReturn(br); - - List<Object> optimizationModelsData = new ArrayList<Object>(); - OptimizationModels testData = new OptimizationModels(); - testData.setVersion("1707.4.1.2-Junit"); - optimizationModelsData.add(testData); - // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody")).thenReturn(optimizationModelsData); - - controller.getOptimizationTemplateData(request, response); - - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelData")); - - logger.debug("response: " + response.getContentAsString()); - - } catch (Exception e) { - logger.error("testGetOptimizationTemplateData", e); - } - - logger.debug("testGetOptimizationTemplateData: exit"); - } - - /** - * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, - * HttpServletResponse) method test - */ - - @Test - public void testGetModelServiceVersionData() { - - logger.debug("testGetModelServiceVersionData: enter"); - - CreateOptimizationController controller = new CreateOptimizationController(); - MockHttpServletResponse response = new MockHttpServletResponse(); - String modelJson = "{\"policyData\":\"TestPolicyBody\"}"; - try { - - CreateOptimizationController.setCommonClassDao(commonClassDao); - - BufferedReader br = new BufferedReader(new StringReader(modelJson)); - // mock the getReader() call - when(request.getReader()).thenReturn(br); - - List<Object> optimizationModelsData = new ArrayList<Object>(); - OptimizationModels testData = new OptimizationModels(); - testData.setVersion("1707.4.1.2-Junit"); - optimizationModelsData.add(testData); - - // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody")).thenReturn(optimizationModelsData); - controller.getModelServiceVersionData(request, response); - - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit")); - - logger.debug("response: " + response.getContentAsString()); - - } catch (Exception e) { - logger.error("testGetModelServiceVersionData", e); - fail("testGetModelServiceVersionData failed due to: " + e); - } - - logger.debug("testGetModelServiceVersionData: exit"); - } - - /** - * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, - * PolicyEntity) method test - */ - - @Test - public void testPrePopulatePolicyData() { - - logger.debug("testPrePopulatePolicyData: enter"); - - CreateOptimizationController controller = new CreateOptimizationController(); - - // populate an entity object for testing - PolicyEntity entity = new PolicyEntity(); - ConfigurationDataEntity configData = new ConfigurationDataEntity(); - configData.setConfigBody(configBodyString); - entity.setConfigurationData(configData); - - JsonNode root = null; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter restAdapter = null; - - try { - root = JsonLoader.fromString(jsonString); - restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - PolicyType policyType = new PolicyType(); - TargetType target = new TargetType(); - - // create guard attribute - AnyOfType anyOfType = new AnyOfType(); - AllOfType alltype = new AllOfType(); - MatchType matchType = new MatchType(); - // set value - AttributeValueType attributeValue1 = new AttributeValueType(); - attributeValue1.getContent().add("True"); - matchType.setAttributeValue(attributeValue1); + } + + /** + * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test + */ + + @Test + public void testSetDataToPolicyRestAdapter() { + + logger.debug("testSetDataToPolicyRestAdapter: enter"); + + CreateOptimizationController controller = new CreateOptimizationController(); + CreateOptimizationController.setCommonClassDao(commonClassDao); + + JsonNode root = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter policyData = null; + try { + root = JsonLoader.fromString(jsonString); + policyData = (PolicyRestAdapter) mapper.readValue( + root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + } catch (Exception e) { + logger.error("testSetDataToPolicyRestAdapter", e); + } + + PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root); + assertTrue( + result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); + + logger.debug("result.getJsonBody() : " + result.getJsonBody()); + logger.debug("testSetDataToPolicyRestAdapter: exit"); + } + + /** + * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse) + * method test + */ + + @Test + public void testGetOptimizationTemplateData() { + + logger.debug("testGetOptimizationTemplateData: enter"); + + CreateOptimizationController controller = new CreateOptimizationController(); + MockHttpServletResponse response = new MockHttpServletResponse(); + String modelJson = "{\"policyData\":\"testPolicyBody\"}"; + try { + + CreateOptimizationController.setCommonClassDao(commonClassDao); + + BufferedReader br = new BufferedReader(new StringReader(modelJson)); + // mock the getReader() call + when(request.getReader()).thenReturn(br); + + List<Object> optimizationModelsData = new ArrayList<Object>(); + OptimizationModels testData = new OptimizationModels(); + testData.setVersion("1707.4.1.2-Junit"); + optimizationModelsData.add(testData); + // mock the getDataById() call with the same MS model name + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", + "testPolicyBody")).thenReturn(optimizationModelsData); + + controller.getOptimizationTemplateData(request, response); + + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("optimizationModelData")); + + logger.debug("response: " + response.getContentAsString()); + + } catch (Exception e) { + logger.error("testGetOptimizationTemplateData", e); + } + + logger.debug("testGetOptimizationTemplateData: exit"); + } + + /** + * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse) + * method test + */ + + @Test + public void testGetModelServiceVersionData() { + + logger.debug("testGetModelServiceVersionData: enter"); + + CreateOptimizationController controller = new CreateOptimizationController(); + MockHttpServletResponse response = new MockHttpServletResponse(); + String modelJson = "{\"policyData\":\"TestPolicyBody\"}"; + try { + + CreateOptimizationController.setCommonClassDao(commonClassDao); + + BufferedReader br = new BufferedReader(new StringReader(modelJson)); + // mock the getReader() call + when(request.getReader()).thenReturn(br); + + List<Object> optimizationModelsData = new ArrayList<Object>(); + OptimizationModels testData = new OptimizationModels(); + testData.setVersion("1707.4.1.2-Junit"); + optimizationModelsData.add(testData); + + // mock the getDataById() call with the same MS model name + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", + "TestPolicyBody")).thenReturn(optimizationModelsData); + controller.getModelServiceVersionData(request, response); + + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("1707.4.1.2-Junit")); + + logger.debug("response: " + response.getContentAsString()); + + } catch (Exception e) { + logger.error("testGetModelServiceVersionData", e); + fail("testGetModelServiceVersionData failed due to: " + e); + } + + logger.debug("testGetModelServiceVersionData: exit"); + } + + /** + * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test + */ + + @Test + public void testPrePopulatePolicyData() { + + logger.debug("testPrePopulatePolicyData: enter"); + + CreateOptimizationController controller = new CreateOptimizationController(); + + // populate an entity object for testing + PolicyEntity entity = new PolicyEntity(); + ConfigurationDataEntity configData = new ConfigurationDataEntity(); + configData.setConfigBody(configBodyString); + entity.setConfigurationData(configData); + + JsonNode root = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter restAdapter = null; + + try { + root = JsonLoader.fromString(jsonString); + restAdapter = (PolicyRestAdapter) mapper.readValue( + root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + PolicyType policyType = new PolicyType(); + TargetType target = new TargetType(); + + // create guard attribute + AnyOfType anyOfType = new AnyOfType(); + AllOfType alltype = new AllOfType(); + MatchType matchType = new MatchType(); + // set value + AttributeValueType attributeValue1 = new AttributeValueType(); + attributeValue1.getContent().add("True"); + matchType.setAttributeValue(attributeValue1); // set Id - AttributeDesignatorType designator = new AttributeDesignatorType(); - designator.setAttributeId("guard"); - matchType.setAttributeDesignator(designator); - alltype.getMatch().add(matchType); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy = new MatchType(); - // set value - AttributeValueType dummyValue = new AttributeValueType(); - dummyValue.getContent().add("dummy"); - matchDummy.setAttributeValue(dummyValue); + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId("guard"); + matchType.setAttributeDesignator(designator); + alltype.getMatch().add(matchType); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy = new MatchType(); + // set value + AttributeValueType dummyValue = new AttributeValueType(); + dummyValue.getContent().add("dummy"); + matchDummy.setAttributeValue(dummyValue); // set Id - AttributeDesignatorType designatorDummy = new AttributeDesignatorType(); - designatorDummy.setAttributeId("dummyId"); - matchDummy.setAttributeDesignator(designatorDummy); - - alltype.getMatch().add(matchDummy); - anyOfType.getAllOf().add(alltype); - - target.getAnyOf().add(anyOfType); - - // create RiskType attribute - AnyOfType anyRiskType = new AnyOfType(); - AllOfType allRiskType = new AllOfType(); - MatchType matchRiskType = new MatchType(); - // set value - AttributeValueType riskTypeValue = new AttributeValueType(); - riskTypeValue.getContent().add("test"); - matchRiskType.setAttributeValue(riskTypeValue); + AttributeDesignatorType designatorDummy = new AttributeDesignatorType(); + designatorDummy.setAttributeId("dummyId"); + matchDummy.setAttributeDesignator(designatorDummy); + + alltype.getMatch().add(matchDummy); + anyOfType.getAllOf().add(alltype); + + target.getAnyOf().add(anyOfType); + + // create RiskType attribute + AnyOfType anyRiskType = new AnyOfType(); + AllOfType allRiskType = new AllOfType(); + MatchType matchRiskType = new MatchType(); + // set value + AttributeValueType riskTypeValue = new AttributeValueType(); + riskTypeValue.getContent().add("test"); + matchRiskType.setAttributeValue(riskTypeValue); // set Id - AttributeDesignatorType designatorRiskType = new AttributeDesignatorType(); - designatorRiskType.setAttributeId("RiskType"); - matchRiskType.setAttributeDesignator(designatorRiskType); - allRiskType.getMatch().add(matchRiskType); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy1 = new MatchType(); - // set value - AttributeValueType dummy1Value = new AttributeValueType(); - dummy1Value.getContent().add("dummy"); - matchDummy1.setAttributeValue(dummy1Value); + AttributeDesignatorType designatorRiskType = new AttributeDesignatorType(); + designatorRiskType.setAttributeId("RiskType"); + matchRiskType.setAttributeDesignator(designatorRiskType); + allRiskType.getMatch().add(matchRiskType); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy1 = new MatchType(); + // set value + AttributeValueType dummy1Value = new AttributeValueType(); + dummy1Value.getContent().add("dummy"); + matchDummy1.setAttributeValue(dummy1Value); // set Id - AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType(); - designatorDummy1.setAttributeId("dummyId"); - matchDummy1.setAttributeDesignator(designatorDummy1); - - allRiskType.getMatch().add(matchDummy1); - - anyRiskType.getAllOf().add(allRiskType); - - target.getAnyOf().add(anyRiskType); - - // create RiskLevel attribute - AnyOfType anyRiskLevel = new AnyOfType(); - AllOfType allRiskLevel = new AllOfType(); - MatchType matchRiskLevel = new MatchType(); - // set value - AttributeValueType riskLevel = new AttributeValueType(); - riskLevel.getContent().add("3"); - matchRiskLevel.setAttributeValue(riskLevel); + AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType(); + designatorDummy1.setAttributeId("dummyId"); + matchDummy1.setAttributeDesignator(designatorDummy1); + + allRiskType.getMatch().add(matchDummy1); + + anyRiskType.getAllOf().add(allRiskType); + + target.getAnyOf().add(anyRiskType); + + // create RiskLevel attribute + AnyOfType anyRiskLevel = new AnyOfType(); + AllOfType allRiskLevel = new AllOfType(); + MatchType matchRiskLevel = new MatchType(); + // set value + AttributeValueType riskLevel = new AttributeValueType(); + riskLevel.getContent().add("3"); + matchRiskLevel.setAttributeValue(riskLevel); // set Id - AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType(); - designatorRiskLevel.setAttributeId("RiskLevel"); - matchRiskLevel.setAttributeDesignator(designatorRiskLevel); - allRiskLevel.getMatch().add(matchRiskLevel); - - // add a dummy MatchType object since while (matchList.size()>1 ...) - MatchType matchDummy2 = new MatchType(); - // set value - AttributeValueType dummy2Value = new AttributeValueType(); - dummy2Value.getContent().add("dummy"); - matchDummy2.setAttributeValue(dummy2Value); + AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType(); + designatorRiskLevel.setAttributeId("RiskLevel"); + matchRiskLevel.setAttributeDesignator(designatorRiskLevel); + allRiskLevel.getMatch().add(matchRiskLevel); + + // add a dummy MatchType object since while (matchList.size()>1 ...) + MatchType matchDummy2 = new MatchType(); + // set value + AttributeValueType dummy2Value = new AttributeValueType(); + dummy2Value.getContent().add("dummy"); + matchDummy2.setAttributeValue(dummy2Value); // set Id - AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType(); - designatorDummy2.setAttributeId("dummyId"); - matchDummy2.setAttributeDesignator(designatorDummy2); - - allRiskLevel.getMatch().add(matchDummy2); - - anyRiskLevel.getAllOf().add(allRiskLevel); - target.getAnyOf().add(anyRiskLevel); - - policyType.setTarget(target); - - restAdapter.setPolicyData(policyType); - - controller.prePopulatePolicyData(restAdapter, entity); - - logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType()); - logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel()); - logger.error("restAdapter.getGuard() : " + restAdapter.getGuard()); - - assertEquals("True", restAdapter.getGuard()); - assertEquals("3", restAdapter.getRiskLevel()); - assertEquals("test", restAdapter.getRiskType()); - - } catch (Exception e) { - logger.error("testPrePopulatePolicyData", e); - fail("testPrePopulatePolicyData failed due to: " + e); - } - - logger.debug("testPrePopulatePolicyData: exit"); - - } - - /** - * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) - * method test - */ - - @Test - public void testSetModelData() { - - logger.debug("testSetModelData: enter"); - - CreateOptimizationController controller = new CreateOptimizationController(); - HttpServletRequest request = createMock(HttpServletRequest.class); - MockHttpServletResponse response = new MockHttpServletResponse(); - expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p"); - expect(request.getMethod()).andReturn("post"); - expect(request.getHeader("Content-length")).andReturn("7809"); - - expect(request.getContentLength()).andReturn(7809); - - try { - // value of fileName needs to be matched to your local directory - String fileName = ""; - try { - ClassLoader classLoader = getClass().getClassLoader(); - fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath(); - } catch (Exception e1) { - logger.error("Exception Occured while loading file"+e1); - } - expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName)); - expect(request.getCharacterEncoding()).andReturn("UTF-8"); - expect(request.getContentLength()).andReturn(1024); - replay(request); - controller.setModelData(request, response); - - } catch (Exception e) { - logger.error("testSetModelData" + e); - e.printStackTrace(); - } - - - logger.debug("testSetModelData: exit"); - } - - /** - * - * @ Get File Stream - * - */ - private class MockServletInputStream extends ServletInputStream { - - InputStream fis = null; - public MockServletInputStream(String fileName) { - try { - fis = new FileInputStream(fileName); - } catch (Exception genExe) { - genExe.printStackTrace(); - } - } - @Override - public int read() throws IOException { - if(fis.available() > 0) { - return fis.read(); - } - return 0; - } - - @Override - public int read(byte[] bytes, int len, int size) throws IOException { - if(fis.available() > 0) { - int length = fis.read(bytes, len, size); - return length; - } - return -1; - } - @Override - public boolean isFinished() { - return false; - } - @Override - public boolean isReady() { - return false; - } - @Override - public void setReadListener(ReadListener arg0) { - - } - } - -}
\ No newline at end of file + AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType(); + designatorDummy2.setAttributeId("dummyId"); + matchDummy2.setAttributeDesignator(designatorDummy2); + + allRiskLevel.getMatch().add(matchDummy2); + + anyRiskLevel.getAllOf().add(allRiskLevel); + target.getAnyOf().add(anyRiskLevel); + + policyType.setTarget(target); + + restAdapter.setPolicyData(policyType); + + controller.prePopulatePolicyData(restAdapter, entity); + + logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType()); + logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel()); + logger.error("restAdapter.getGuard() : " + restAdapter.getGuard()); + + assertEquals("True", restAdapter.getGuard()); + assertEquals("3", restAdapter.getRiskLevel()); + assertEquals("test", restAdapter.getRiskType()); + + } catch (Exception e) { + logger.error("testPrePopulatePolicyData", e); + fail("testPrePopulatePolicyData failed due to: " + e); + } + + logger.debug("testPrePopulatePolicyData: exit"); + + } + + /** + * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test + */ + + @Test + public void testSetModelData() { + + logger.debug("testSetModelData: enter"); + + CreateOptimizationController controller = new CreateOptimizationController(); + HttpServletRequest request = createMock(HttpServletRequest.class); + MockHttpServletResponse response = new MockHttpServletResponse(); + expect(request.getContentType()) + .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p"); + expect(request.getMethod()).andReturn("post"); + expect(request.getHeader("Content-length")).andReturn("7809"); + + expect(request.getContentLength()).andReturn(7809); + + try { + // value of fileName needs to be matched to your local directory + String fileName = ""; + try { + ClassLoader classLoader = getClass().getClassLoader(); + fileName = + new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()) + .getAbsolutePath(); + } catch (Exception e1) { + logger.error("Exception Occured while loading file" + e1); + } + expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName)); + expect(request.getCharacterEncoding()).andReturn("UTF-8"); + expect(request.getContentLength()).andReturn(1024); + replay(request); + controller.setModelData(request, response); + + } catch (Exception e) { + logger.error("testSetModelData" + e); + e.printStackTrace(); + } + + logger.debug("testSetModelData: exit"); + } + + /** + * + * @ Get File Stream + * + */ + private class MockServletInputStream extends ServletInputStream { + + InputStream fis = null; + + public MockServletInputStream(String fileName) { + try { + fis = new FileInputStream(fileName); + } catch (Exception genExe) { + genExe.printStackTrace(); + } + } + + @Override + public int read() throws IOException { + if (fis.available() > 0) { + return fis.read(); + } + return 0; + } + + @Override + public int read(byte[] bytes, int len, int size) throws IOException { + if (fis.available() > 0) { + int length = fis.read(bytes, len, size); + return length; + } + return -1; + } + + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener arg0) { + + } + } +} diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java index ba88dd314..f2ecea504 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +24,10 @@ package org.onap.policy.controller; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; - import java.io.UnsupportedEncodingException; import java.nio.file.Path; import java.nio.file.Paths; - import javax.servlet.http.HttpServletRequest; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -39,89 +38,93 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.xacml.std.pap.StdEngine; import org.springframework.mock.web.MockHttpServletResponse; -public class DashboardControllerTest{ - private static Logger logger = FlexLogger.getLogger(DashboardControllerTest.class); - - private static CommonClassDao commonClassDao; - private static SystemLogDbDao systemDAO; - private static PolicyController ctrl = null; - private HttpServletRequest request = null; - private DashboardController controller = null; - private MockHttpServletResponse response = null; - private Path repo; - StdEngine engine = null; - - @Before - public void setUp() throws Exception { - logger.info("setUp: Entering"); - controller = new DashboardController(); - commonClassDao = Mockito.mock(CommonClassDao.class); - systemDAO = Mockito.mock(SystemLogDbDao.class); - controller.setSystemLogDbDao(systemDAO); - controller.setCommonClassDao(commonClassDao); - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - repo = Paths.get("src/test/resources/pdps"); - engine = new StdEngine(repo); - ctrl = new PolicyController(); - PolicyController.setPapEngine(engine); - controller.setPolicyController(ctrl); - logger.info("setUp: exit"); - } - - @Test - public void testGetData() { - try { - controller.getData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("availableLoggingDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } +public class DashboardControllerTest { + private static Logger logger = FlexLogger.getLogger(DashboardControllerTest.class); - @Test - public void testGetPAPStatusData() { - try { - controller.getPAPStatusData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("papTableDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } + private static CommonClassDao commonClassDao; + private static SystemLogDbDao systemDAO; + private static PolicyController ctrl = null; + private HttpServletRequest request = null; + private DashboardController controller = null; + private MockHttpServletResponse response = null; + private Path repo; + StdEngine engine = null; - @Test - public void testGetPDPStatusData() { - try { - controller.getPDPStatusData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("pdpTableDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + controller = new DashboardController(); + commonClassDao = Mockito.mock(CommonClassDao.class); + systemDAO = Mockito.mock(SystemLogDbDao.class); + controller.setSystemLogDbDao(systemDAO); + controller.setCommonClassDao(commonClassDao); + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + repo = Paths.get("src/test/resources/pdps"); + engine = new StdEngine(repo); + ctrl = new PolicyController(); + PolicyController.setPapEngine(engine); + controller.setPolicyController(ctrl); + logger.info("setUp: exit"); + } - @Test - public void testGetPolicyActivityData() { - try { - controller.getPolicyActivityData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("policyActivityTableDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } + @Test + public void testGetData() { + try { + controller.getData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("availableLoggingDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } - @Test - public void testGetSystemAlertData() { - try { - controller.getSystemAlertData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("systemAlertsTableDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } -} + @Test + public void testGetPAPStatusData() { + try { + controller.getPAPStatusData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("papTableDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } + + @Test + public void testGetPDPStatusData() { + try { + controller.getPDPStatusData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pdpTableDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } + @Test + public void testGetPolicyActivityData() { + try { + controller.getPolicyActivityData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("policyActivityTableDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } + + @Test + public void testGetSystemAlertData() { + try { + controller.getSystemAlertData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("systemAlertsTableDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } +} diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java index 55a2288c7..1c1c0fbbd 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,15 +22,12 @@ package org.onap.policy.controller; import static org.junit.Assert.assertTrue; - import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; - import javax.servlet.http.HttpServletRequest; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -40,47 +39,45 @@ import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroupStatus; import org.springframework.mock.web.MockHttpServletResponse; +public class PDPControllerTest extends Mockito { + + private static Logger logger = FlexLogger.getLogger(PDPControllerTest.class); + private Set<OnapPDPGroup> groupsData; + private Set<StdPDPGroup> groups; + private static List<Object> rolesdata; + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + rolesdata = new ArrayList<>(); + Roles roles = new Roles(); + roles.setLoginId("Test"); + roles.setRole("super-admin"); + Roles roles1 = new Roles(); + roles1.setLoginId("Test"); + roles1.setRole("admin"); + roles1.setScope("['com','Test']"); + rolesdata.add(roles); + rolesdata.add(roles1); -public class PDPControllerTest extends Mockito{ + groups = new HashSet<>(); + StdPDPGroup group = new StdPDPGroup(); + group.setId("default"); + group.setDefault(true); + group.setName("default"); + group.setDescription("The default group where new PDP's are put."); + group.setStatus(new StdPDPGroupStatus()); + groups.add(group); + groupsData = new HashSet<>(); + for (OnapPDPGroup g : this.groups) { + groupsData.add(g); + } + } - private static Logger logger = FlexLogger.getLogger(PDPControllerTest.class); - private Set<OnapPDPGroup> groupsData; - private Set<StdPDPGroup> groups; - private static List<Object> rolesdata; - - @Before - public void setUp() throws Exception{ - logger.info("setUp: Entering"); - rolesdata = new ArrayList<>(); - Roles roles = new Roles(); - roles.setLoginId("Test"); - roles.setRole("super-admin"); - Roles roles1 = new Roles(); - roles1.setLoginId("Test"); - roles1.setRole("admin"); - roles1.setScope("['com','Test']"); - rolesdata.add(roles); - rolesdata.add(roles1); - - groups = new HashSet<>(); - StdPDPGroup group = new StdPDPGroup(); - group.setId("default"); - group.setDefault(true); - group.setName("default"); - group.setDescription("The default group where new PDP's are put."); - group.setStatus(new StdPDPGroupStatus()); - groups.add(group); - groupsData = new HashSet<>(); - for (OnapPDPGroup g : this.groups) { - groupsData.add(g); - } - } - - @Test - public void testPDPGroupData(){ - HttpServletRequest request = mock(HttpServletRequest.class); - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void testPDPGroupData() { + HttpServletRequest request = mock(HttpServletRequest.class); + MockHttpServletResponse response = new MockHttpServletResponse(); PolicyController controller = mock(PolicyController.class); PDPController pdpController = new PDPController(); pdpController.setJunit(true);; @@ -89,10 +86,10 @@ public class PDPControllerTest extends Mockito{ when(controller.getRoles("Test")).thenReturn(rolesdata); pdpController.getPDPGroupEntityData(request, response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("data")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - } - } - + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("data")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java index 6f20a6770..65077ae01 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,12 +25,9 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.ArrayList; import java.util.List; - import javax.script.SimpleBindings; - import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; @@ -41,30 +40,33 @@ import org.onap.policy.rest.jpa.PolicyEntity; public class PolicyControllerTest { - private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class); - private static CommonClassDao commonClassDao; - - @Before - public void setUp() throws Exception{ - logger.info("setUp: Entering"); + private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class); + private static CommonClassDao commonClassDao; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); PolicyController.setCommonClassDao(commonClassDao); List<Object> data = new ArrayList<>(); String policyData = ""; try { - ClassLoader classLoader = getClass().getClassLoader(); - policyData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); - } catch (Exception e1) { - e1.printStackTrace(); - } + ClassLoader classLoader = getClass().getClassLoader(); + policyData = IOUtils + .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); + } catch (Exception e1) { + e1.printStackTrace(); + } PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyData); entity.setScope("com"); data.add(entity); - - when(commonClassDao.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'", new SimpleBindings())).thenReturn(data); - + + when(commonClassDao.getDataByQuery( + "FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'", + new SimpleBindings())).thenReturn(data); + FunctionDefinition fnDefinition = new FunctionDefinition(); fnDefinition.setXacmlid("Test"); fnDefinition.setShortname("Test"); @@ -74,18 +76,18 @@ public class PolicyControllerTest { List<Object> fnObjects = new ArrayList<>(); fnObjects.add(fnDefinition); when(commonClassDao.getData(FunctionDefinition.class)).thenReturn(fnObjects); - } - - @Test - public void testInit(){ - PolicyController controller = new PolicyController(); - PolicyController.setjUnit(true); - controller.init(); - try{ - assertTrue(PolicyController.dropDownMap.size() > 0); - }catch(Exception e){ - logger.error("Exception Occured"+e); - fail(); - } - } + } + + @Test + public void testInit() { + PolicyController controller = new PolicyController(); + PolicyController.setjUnit(true); + controller.init(); + try { + assertTrue(PolicyController.dropDownMap.size() > 0); + } catch (Exception e) { + logger.error("Exception Occured" + e); + fail(); + } + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java index 49249cad3..476eb6728 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,34 +43,36 @@ import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) public class PolicyNotificationControllerTest { - @PrepareForTest({UserUtils.class}) - @Test - public void testWatch() throws IOException{ - // Mock user utilities - PowerMockito.mockStatic(UserUtils.class); - User user = new User(); - user.setOrgUserId("testID"); - when(UserUtils.getUserSession(any())).thenReturn(user); - - // Mock database - CommonClassDao dao = Mockito.mock(CommonClassDao.class); - Mockito.when(dao.getDataByQuery(any(), any())).thenReturn(Collections.emptyList()); + @PrepareForTest({UserUtils.class}) + @Test + public void testWatch() throws IOException { + // Mock user utilities + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + user.setOrgUserId("testID"); + when(UserUtils.getUserSession(any())).thenReturn(user); + + // Mock database + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + Mockito.when(dao.getDataByQuery(any(), any())).thenReturn(Collections.emptyList()); - // Test watch - PolicyNotificationController controller = new PolicyNotificationController(); - controller.commonClassDao = dao; - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n"); - MockHttpServletResponse response = new MockHttpServletResponse(); - ModelAndView model = controller.watchPolicy(request, response); - assertNull(model); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + // Test watch + PolicyNotificationController controller = new PolicyNotificationController(); + controller.commonClassDao = dao; + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setBodyContent( + "{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n"); + MockHttpServletResponse response = new MockHttpServletResponse(); + ModelAndView model = controller.watchPolicy(request, response); + assertNull(model); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - // Negative test watch - request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n"); - response = new MockHttpServletResponse(); - model = controller.watchPolicy(request, response); - assertNull(model); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - } + // Negative test watch + request.setBodyContent( + "{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n"); + response = new MockHttpServletResponse(); + model = controller.watchPolicy(request, response); + assertNull(model); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java index 96b27b178..d665aae5e 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,14 +25,11 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -42,65 +41,70 @@ import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.mock.web.MockHttpServletResponse; public class PolicyRolesControllerTest { - private static Logger logger = FlexLogger.getLogger(PolicyRolesControllerTest.class); - private HttpServletRequest request = null; - private MockHttpServletResponse response = null; - private PolicyRolesController controller = null; - private static CommonClassDao commonClassDao; - - @Before - public void setUp() throws Exception { - logger.info("setUp: Entering"); - controller = new PolicyRolesController(); - commonClassDao = Mockito.mock(CommonClassDao.class); - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); - controller.setCommonClassDao(commonClassDao); - - HttpSession mockSession = mock(HttpSession.class); + private static Logger logger = FlexLogger.getLogger(PolicyRolesControllerTest.class); + private HttpServletRequest request = null; + private MockHttpServletResponse response = null; + private PolicyRolesController controller = null; + private static CommonClassDao commonClassDao; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + controller = new PolicyRolesController(); + commonClassDao = Mockito.mock(CommonClassDao.class); + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); + controller.setCommonClassDao(commonClassDao); + + HttpSession mockSession = mock(HttpSession.class); User user = new User(); - user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); - Mockito.when(request.getSession(false)).thenReturn(mockSession); - - logger.info("setUp: exit"); - } + user.setOrgUserId("Test"); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) + .thenReturn(user); + Mockito.when(request.getSession(false)).thenReturn(mockSession); - @Test - public void testGetPolicyRolesEntityData() { - try { - controller.getPolicyRolesEntityData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } -} + logger.info("setUp: exit"); + } - @Test - public void testGetPolicyScopesEntityData() { - try { - controller.getPolicyScopesEntityData(request, response); - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("scopeDatas")); - } catch (UnsupportedEncodingException e) { - logger.error("Exception Occured"+e); - fail(); - } - } + @Test + public void testGetPolicyRolesEntityData() { + try { + controller.getPolicyRolesEntityData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("rolesDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } - @Test - public void testSaveRolesEntityData() { - logger.info("PolicyRolesControllerTest: Entering"); - String jsonString = "{\"editRoleData\": {\"id\": 1,\"loginId\": {\"userLoginId\" : \"test\", \"userName\" : \"test\"},\"role\":\"test\",\"scope\":[\"scope\"]}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ - when(request.getReader()).thenReturn(br); - controller.SaveRolesEntityData(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); - } catch (Exception e) { - fail("Exception: " + e); - } - logger.info("PolicyRolesControllerTest: exit"); - } -} + @Test + public void testGetPolicyScopesEntityData() { + try { + controller.getPolicyScopesEntityData(request, response); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("scopeDatas")); + } catch (UnsupportedEncodingException e) { + logger.error("Exception Occured" + e); + fail(); + } + } + @Test + public void testSaveRolesEntityData() { + logger.info("PolicyRolesControllerTest: Entering"); + String jsonString = + "{\"editRoleData\": {\"id\": 1,\"loginId\": {\"userLoginId\" : \"test\", \"userName\" : \"test\"}," + + "\"role\":\"test\",\"scope\":[\"scope\"]}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { + when(request.getReader()).thenReturn(br); + controller.SaveRolesEntityData(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("rolesDatas")); + } catch (Exception e) { + fail("Exception: " + e); + } + logger.info("PolicyRolesControllerTest: exit"); + } +} diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java index 580fc30f9..2ad6d6a7e 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +31,13 @@ import com.mockrunner.mock.web.MockHttpServletRequest; import com.mockrunner.mock.web.MockHttpServletResponse; public class PolicyValidationControllerTest { - @Test - public void testValidate() throws IOException { - PolicyValidationController controller = new PolicyValidationController(); - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - ModelAndView model = controller.validatePolicy(request, response); - assertNull(model); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - } + @Test + public void testValidate() throws IOException { + PolicyValidationController controller = new PolicyValidationController(); + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + ModelAndView model = controller.validatePolicy(request, response); + assertNull(model); + assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java index 63ca29d90..e7212f109 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,15 +26,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; - import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; - import javax.script.SimpleBindings; - import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.h2.tools.Server; import org.hibernate.SessionFactory; @@ -54,413 +53,410 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; -public class CommonClassDaoImplTest{ - - private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class); - - SessionFactory sessionFactory; - Server server; - CommonClassDaoImpl commonClassDao; - - @Before - public void setUp() throws Exception{ - try{ - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("org.h2.Driver"); - // In-memory DB for testing - dataSource.setUrl("jdbc:h2:mem:test"); - dataSource.setUsername("sa"); - dataSource.setPassword(""); - LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); - sessionBuilder.scanPackages("org.onap.*", "com.*"); - - Properties properties = new Properties(); - properties.put("hibernate.show_sql", "false"); - properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - properties.put("hibernate.hbm2ddl.auto", "drop"); - properties.put("hibernate.hbm2ddl.auto", "create"); - - sessionBuilder.addProperties(properties); - sessionFactory = sessionBuilder.buildSessionFactory(); - - // Set up dao with SessionFactory - commonClassDao = new CommonClassDaoImpl(); - CommonClassDaoImpl.setSessionfactory(sessionFactory); - PolicyController.setLogTableLimit("1"); - HibernateSession.setSession(sessionFactory); - SystemLogDB data1 = new SystemLogDB(); - data1.setDate(new Date()); - data1.setLogtype("INFO"); - data1.setRemote("Test"); - data1.setSystem("Test"); - data1.setType("Test"); - SystemLogDB data2 = new SystemLogDB(); - data2.setDate(new Date()); - data2.setLogtype("error"); - data2.setRemote("Test"); - data2.setSystem("Test"); - data2.setType("Test"); - HibernateSession.getSession().save(data1); - HibernateSession.getSession().save(data2); - // Create TCP server for troubleshooting - server = Server.createTcpServer("-tcpAllowOthers").start(); - System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test"); - - }catch(Exception e){ - System.err.println(e); - fail(); - } - } - - @Test - @Transactional +public class CommonClassDaoImplTest { + + private static Logger logger = FlexLogger.getLogger(CommonClassDaoImplTest.class); + + SessionFactory sessionFactory; + Server server; + CommonClassDaoImpl commonClassDao; + + @Before + public void setUp() throws Exception { + try { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + // In-memory DB for testing + dataSource.setUrl("jdbc:h2:mem:test"); + dataSource.setUsername("sa"); + dataSource.setPassword(""); + LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); + sessionBuilder.scanPackages("org.onap.*", "com.*"); + + Properties properties = new Properties(); + properties.put("hibernate.show_sql", "false"); + properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.put("hibernate.hbm2ddl.auto", "drop"); + properties.put("hibernate.hbm2ddl.auto", "create"); + + sessionBuilder.addProperties(properties); + sessionFactory = sessionBuilder.buildSessionFactory(); + + // Set up dao with SessionFactory + commonClassDao = new CommonClassDaoImpl(); + CommonClassDaoImpl.setSessionfactory(sessionFactory); + PolicyController.setLogTableLimit("1"); + HibernateSession.setSession(sessionFactory); + SystemLogDB data1 = new SystemLogDB(); + data1.setDate(new Date()); + data1.setLogtype("INFO"); + data1.setRemote("Test"); + data1.setSystem("Test"); + data1.setType("Test"); + SystemLogDB data2 = new SystemLogDB(); + data2.setDate(new Date()); + data2.setLogtype("error"); + data2.setRemote("Test"); + data2.setSystem("Test"); + data2.setType("Test"); + HibernateSession.getSession().save(data1); + HibernateSession.getSession().save(data2); + // Create TCP server for troubleshooting + server = Server.createTcpServer("-tcpAllowOthers").start(); + System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test"); + + } catch (Exception e) { + System.err.println(e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void testDB(){ - try{ - // Add data - UserInfo userinfo = new UserInfo(); - userinfo.setUserLoginId("Test"); - userinfo.setUserName("Test"); - commonClassDao.save(userinfo); - OnapName onapName = new OnapName(); - onapName.setOnapName("Test"); - onapName.setUserCreatedBy(userinfo); - onapName.setUserModifiedBy(userinfo); - onapName.setModifiedDate(new Date()); - commonClassDao.save(onapName); - - - List<Object> list = commonClassDao.getData(OnapName.class); - assertTrue(list.size() == 1); - logger.debug(list.size()); - logger.debug(list.get(0)); - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - @Transactional + public void testDB() { + try { + // Add data + UserInfo userinfo = new UserInfo(); + userinfo.setUserLoginId("Test"); + userinfo.setUserName("Test"); + commonClassDao.save(userinfo); + OnapName onapName = new OnapName(); + onapName.setOnapName("Test"); + onapName.setUserCreatedBy(userinfo); + onapName.setUserModifiedBy(userinfo); + onapName.setModifiedDate(new Date()); + commonClassDao.save(onapName); + + List<Object> list = commonClassDao.getData(OnapName.class); + assertTrue(list.size() == 1); + logger.debug(list.size()); + logger.debug(list.get(0)); + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void testUser(){ - try{ - // Add data - UserInfo userinfo = new UserInfo(); - String loginId_userName = "Test"; - userinfo.setUserLoginId(loginId_userName); - userinfo.setUserName(loginId_userName); - commonClassDao.save(userinfo); - - - List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); - - assertEquals(1, dataCur.size()); - UserInfo cur = (UserInfo) dataCur.get(0); - assertEquals(loginId_userName, cur.getUserLoginId()); - assertEquals(loginId_userName, cur.getUserName()); - - assertFalse(dataCur.isEmpty()); - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - @Transactional + public void testUser() { + try { + // Add data + UserInfo userinfo = new UserInfo(); + String loginId_userName = "Test"; + userinfo.setUserLoginId(loginId_userName); + userinfo.setUserName(loginId_userName); + commonClassDao.save(userinfo); + + List<Object> dataCur = + commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); + + assertEquals(1, dataCur.size()); + UserInfo cur = (UserInfo) dataCur.get(0); + assertEquals(loginId_userName, cur.getUserLoginId()); + assertEquals(loginId_userName, cur.getUserName()); + + assertFalse(dataCur.isEmpty()); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_DashboardController(){ - try{ - // Add data - PolicyEntity pe = new PolicyEntity(); - String name = "TestPolicy"; - pe.setPolicyName(name); - pe.setPolicyData("dummyData"); - pe.prePersist(); - pe.setScope("dummyScope"); - pe.setDescription("descr"); - pe.setDeleted(false); - pe.setCreatedBy("Test"); - commonClassDao.save(pe); - - List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); - - assertTrue(1 == dataCur.size()); - assertTrue( dataCur.get(0) instanceof PolicyEntity); - assertEquals( name, ((PolicyEntity)dataCur.get(0)).getPolicyName()); - assertEquals( pe, ((PolicyEntity)dataCur.get(0))); - - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - @Transactional + public void getDataByQuery_DashboardController() { + try { + // Add data + PolicyEntity pe = new PolicyEntity(); + String name = "TestPolicy"; + pe.setPolicyName(name); + pe.setPolicyData("dummyData"); + pe.prePersist(); + pe.setScope("dummyScope"); + pe.setDescription("descr"); + pe.setDeleted(false); + pe.setCreatedBy("Test"); + commonClassDao.save(pe); + + List<Object> dataCur = + commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); + + assertTrue(1 == dataCur.size()); + assertTrue(dataCur.get(0) instanceof PolicyEntity); + assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName()); + assertEquals(pe, ((PolicyEntity) dataCur.get(0))); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_AutoPushController(){ - try{ - // Add data - PolicyVersion pv = new PolicyVersion(); - pv.setActiveVersion(2); - pv.setPolicyName("myPname"); - pv.prePersist(); - pv.setCreatedBy("Test"); - pv.setModifiedBy("Test"); - - PolicyVersion pv2 = new PolicyVersion(); - pv2.setActiveVersion(1); - pv2.setPolicyName("test"); - pv2.prePersist(); - pv2.setCreatedBy("Test"); - pv2.setModifiedBy("Test"); - - commonClassDao.save(pv); - commonClassDao.save(pv2); - - String scope = "my"; - scope += "%"; - String query = "From PolicyVersion where policy_name like :scope and id > 0"; - SimpleBindings params = new SimpleBindings(); - params.put("scope", scope); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); - - - assertTrue(1 == dataCur.size()); - assertEquals(pv, (PolicyVersion) dataCur.get(0)); - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - @Transactional + public void getDataByQuery_AutoPushController() { + try { + // Add data + PolicyVersion pv = new PolicyVersion(); + pv.setActiveVersion(2); + pv.setPolicyName("myPname"); + pv.prePersist(); + pv.setCreatedBy("Test"); + pv.setModifiedBy("Test"); + + PolicyVersion pv2 = new PolicyVersion(); + pv2.setActiveVersion(1); + pv2.setPolicyName("test"); + pv2.prePersist(); + pv2.setCreatedBy("Test"); + pv2.setModifiedBy("Test"); + + commonClassDao.save(pv); + commonClassDao.save(pv2); + + String scope = "my"; + scope += "%"; + String query = "From PolicyVersion where policy_name like :scope and id > 0"; + SimpleBindings params = new SimpleBindings(); + params.put("scope", scope); + List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + + assertTrue(1 == dataCur.size()); + assertEquals(pv, (PolicyVersion) dataCur.get(0)); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_PolicyNotificationMail(){ - try{ - // Add data - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - String policyFileName = "banana"; - watch.setLoginIds("Test"); - watch.setPolicyName("bananaWatch"); - commonClassDao.save(watch); - - if(policyFileName.contains("/")){ - policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); - policyFileName = policyFileName.replace("/", File.separator); - } - if(policyFileName.contains("\\")){ - policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); - policyFileName = policyFileName.replace("\\", "\\\\"); - } - - - // Current Implementation - policyFileName += "%"; - String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; - SimpleBindings params = new SimpleBindings(); - params.put("policyFileName", policyFileName); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); - - // Assertions - assertTrue(dataCur.size() == 1); - assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - - @Test - @Transactional + public void getDataByQuery_PolicyNotificationMail() { + try { + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String policyFileName = "banana"; + watch.setLoginIds("Test"); + watch.setPolicyName("bananaWatch"); + commonClassDao.save(watch); + + if (policyFileName.contains("/")) { + policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); + policyFileName = policyFileName.replace("/", File.separator); + } + if (policyFileName.contains("\\")) { + policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); + policyFileName = policyFileName.replace("\\", "\\\\"); + } + + // Current Implementation + policyFileName += "%"; + String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; + SimpleBindings params = new SimpleBindings(); + params.put("policyFileName", policyFileName); + List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_PolicyController(){ - try{ - // Add data - PolicyEntity pe = new PolicyEntity(); - String name = "actionDummy"; - pe.setPolicyName(name); - pe.setPolicyData("dummyData"); - pe.prePersist(); - pe.setScope("dummyScope"); - pe.setDescription("descr"); - pe.setDeleted(false); - pe.setCreatedBy("Test"); - commonClassDao.save(pe); - - String dbCheckName = "dummyScope:action"; - String[] splitDBCheckName = dbCheckName.split(":"); - - - // Current Implementation - String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; - SimpleBindings params = new SimpleBindings(); - params.put("splitDBCheckName1", splitDBCheckName[1] + "%"); - params.put("splitDBCheckName0", splitDBCheckName[0]); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); - - // Assertions - assertTrue(dataCur.size() == 1); - assertTrue(dataCur.get(0) instanceof PolicyEntity); - assertEquals(pe, (PolicyEntity) dataCur.get(0)); - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - @Transactional + public void getDataByQuery_PolicyController() { + try { + // Add data + PolicyEntity pe = new PolicyEntity(); + String name = "actionDummy"; + pe.setPolicyName(name); + pe.setPolicyData("dummyData"); + pe.prePersist(); + pe.setScope("dummyScope"); + pe.setDescription("descr"); + pe.setDeleted(false); + pe.setCreatedBy("Test"); + commonClassDao.save(pe); + + String dbCheckName = "dummyScope:action"; + String[] splitDBCheckName = dbCheckName.split(":"); + + // Current Implementation + String query = + "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; + SimpleBindings params = new SimpleBindings(); + params.put("splitDBCheckName1", splitDBCheckName[1] + "%"); + params.put("splitDBCheckName0", splitDBCheckName[0]); + List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof PolicyEntity); + assertEquals(pe, (PolicyEntity) dataCur.get(0)); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_PolicyNotificationController(){ - try{ - // Add data - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - String finalName = "banana"; // Policy File Name - String userId = "Test"; - watch.setLoginIds(userId); - watch.setPolicyName(finalName); - commonClassDao.save(watch); - - - // Current Implementation - String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; - SimpleBindings params = new SimpleBindings(); - params.put("finalName", finalName); - params.put("userId", userId); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); - - // Assertions - assertTrue(dataCur.size() == 1); - assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) ); - - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - - /* Test for SQL Injection Protection - */ - - @Test - @Transactional + public void getDataByQuery_PolicyNotificationController() { + try { + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String finalName = "banana"; // Policy File Name + String userId = "Test"; + watch.setLoginIds(userId); + watch.setPolicyName(finalName); + commonClassDao.save(watch); + + // Current Implementation + String query = + "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() == 1); + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + /* + * Test for SQL Injection Protection + */ + + @Test + @Transactional @Rollback(true) - public void getDataByQuery_PolicyNotificationController_Injection(){ - try{ - // Add data - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - String userId = "Test"; - watch.setLoginIds(userId); - watch.setPolicyName("banana"); - commonClassDao.save(watch); - - WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable(); - watch2.setLoginIds(userId); - watch2.setPolicyName("banana2"); - commonClassDao.save(watch2); - - // SQL Injection attempt - String finalName = "banana' OR '1'='1"; - - - // Current Implementation - String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; - SimpleBindings params = new SimpleBindings(); - params.put("finalName", finalName); - params.put("userId", userId); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); - - // Assertions - assertTrue(dataCur.size() <= 1); - - if(dataCur.size() >= 1){ - assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); - assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); - } - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - @Test - public void testCommonClassDaoImplMethods(){ - try{ - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId("TestID"); - userInfo.setUserName("Test"); - commonClassDao.save(userInfo); - List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test"); - assertTrue(data.size() == 1); - UserInfo userInfoUpdate = (UserInfo) data.get(0); - userInfoUpdate.setUserName("Test1"); - commonClassDao.update(userInfoUpdate); - List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId"); - assertTrue(data1.size() == 1); - UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1"); - assertTrue("TestID".equals(data2.getUserLoginId())); - List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class); - assertTrue(data3.size() == 1); - PolicyRoles roles = new PolicyRoles(); - roles.setRole("admin"); - roles.setLoginId(userInfo); - roles.setScope("test"); - commonClassDao.save(roles); - List<PolicyRoles> roles1 = commonClassDao.getUserRoles(); - assertTrue(roles1.size() == 1); - List<String> multipleData = new ArrayList<>(); - multipleData.add("TestID:Test1"); - List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData); - assertTrue(data4.size() == 1); - commonClassDao.delete(data2); - }catch(Exception e){ - logger.debug("Exception Occured"+e); - fail(); - } - } - - - - @Test - public final void testGetLoggingData() { - SystemLogDbDaoImpl system = new SystemLogDbDaoImpl(); - PolicyController.setjUnit(true); - try{ - assertTrue(system.getLoggingData() != null); - }catch(Exception e){ - fail(); - } - } - - @Test - public final void testGetSystemAlertData() { - SystemLogDbDaoImpl system = new SystemLogDbDaoImpl(); - PolicyController.setjUnit(true); - try{ - assertTrue(system.getSystemAlertData() != null); - }catch(Exception e){ - fail(); - } - } - - @After - public void deleteDB(){ - sessionFactory.close(); - server.stop(); - - } + public void getDataByQuery_PolicyNotificationController_Injection() { + try { + // Add data + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + String userId = "Test"; + watch.setLoginIds(userId); + watch.setPolicyName("banana"); + commonClassDao.save(watch); + + WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable(); + watch2.setLoginIds(userId); + watch2.setPolicyName("banana2"); + commonClassDao.save(watch2); + + // SQL Injection attempt + String finalName = "banana' OR '1'='1"; + + // Current Implementation + String query = + "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + + // Assertions + assertTrue(dataCur.size() <= 1); + + if (dataCur.size() >= 1) { + assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); + assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); + assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0))); + } + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + public void testCommonClassDaoImplMethods() { + try { + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("TestID"); + userInfo.setUserName("Test"); + commonClassDao.save(userInfo); + List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", + "TestID:Test"); + assertTrue(data.size() == 1); + UserInfo userInfoUpdate = (UserInfo) data.get(0); + userInfoUpdate.setUserName("Test1"); + commonClassDao.update(userInfoUpdate); + List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId"); + assertTrue(data1.size() == 1); + UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, + "userLoginId:userName", "TestID:Test1"); + assertTrue("TestID".equals(data2.getUserLoginId())); + List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", + "userLoginId:userName", UserInfo.class); + assertTrue(data3.size() == 1); + PolicyRoles roles = new PolicyRoles(); + roles.setRole("admin"); + roles.setLoginId(userInfo); + roles.setScope("test"); + commonClassDao.save(roles); + List<PolicyRoles> roles1 = commonClassDao.getUserRoles(); + assertTrue(roles1.size() == 1); + List<String> multipleData = new ArrayList<>(); + multipleData.add("TestID:Test1"); + List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, + "userLoginId:userName", multipleData); + assertTrue(data4.size() == 1); + commonClassDao.delete(data2); + } catch (Exception e) { + logger.debug("Exception Occured" + e); + fail(); + } + } + + @Test + public final void testGetLoggingData() { + SystemLogDbDaoImpl system = new SystemLogDbDaoImpl(); + PolicyController.setjUnit(true); + try { + assertTrue(system.getLoggingData() != null); + } catch (Exception e) { + fail(); + } + } + + @Test + public final void testGetSystemAlertData() { + SystemLogDbDaoImpl system = new SystemLogDbDaoImpl(); + PolicyController.setjUnit(true); + try { + assertTrue(system.getSystemAlertData() != null); + } catch (Exception e) { + fail(); + } + } + + @After + public void deleteDB() { + sessionFactory.close(); + server.stop(); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java index 920cc97f8..5117a05da 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,87 +33,87 @@ import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import com.att.research.xacml.api.pap.PAPException; public class PDPGroupContainerTest { - private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class); - private PDPGroupContainer container = new PDPGroupContainer(engine); - - @Test - public void testContainer() throws PAPException { - Object itemId = new Object(); - assertEquals(container.isSupported(itemId), false); - - container.refreshGroups(); - assertEquals(container.getGroups().size(), 0); - - OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); - container.makeDefault(group); - OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); - container.removeGroup(group, newGroup); - OnapPDP pdp = Mockito.mock(OnapPDP.class); - container.updatePDP(pdp); - container.updateGroup(group); - assertNull(container.getContainerPropertyIds()); - assertEquals(container.getItemIds().size(), 0); - assertEquals(container.getType(itemId), null); - assertEquals(container.size(), 0); - assertEquals(container.containsId(itemId), false); - String name = "testName"; - String description = "testDescription"; - container.addNewGroup(name, description); - String id = "testID"; - int jmxport = 0; - container.addNewPDP(id, newGroup, name, description, jmxport); - container.movePDP(pdp, newGroup); - ItemSetChangeListener listener = null; - container.addItemSetChangeListener(listener); - container.nextItemId(itemId); - container.prevItemId(itemId); - container.firstItemId(); - container.lastItemId(); - container.isFirstId(itemId); - container.isLastId(itemId); - container.indexOfId(itemId); - assertEquals(container.getItemIds().size(), 0); - container.removeItem(itemId); - container.removePDP(pdp, newGroup); - } + private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class); + private PDPGroupContainer container = new PDPGroupContainer(engine); + + @Test + public void testContainer() throws PAPException { + Object itemId = new Object(); + assertEquals(container.isSupported(itemId), false); + + container.refreshGroups(); + assertEquals(container.getGroups().size(), 0); + + OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); + container.makeDefault(group); + OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); + container.removeGroup(group, newGroup); + OnapPDP pdp = Mockito.mock(OnapPDP.class); + container.updatePDP(pdp); + container.updateGroup(group); + assertNull(container.getContainerPropertyIds()); + assertEquals(container.getItemIds().size(), 0); + assertEquals(container.getType(itemId), null); + assertEquals(container.size(), 0); + assertEquals(container.containsId(itemId), false); + String name = "testName"; + String description = "testDescription"; + container.addNewGroup(name, description); + String id = "testID"; + int jmxport = 0; + container.addNewPDP(id, newGroup, name, description, jmxport); + container.movePDP(pdp, newGroup); + ItemSetChangeListener listener = null; + container.addItemSetChangeListener(listener); + container.nextItemId(itemId); + container.prevItemId(itemId); + container.firstItemId(); + container.lastItemId(); + container.isFirstId(itemId); + container.isLastId(itemId); + container.indexOfId(itemId); + assertEquals(container.getItemIds().size(), 0); + container.removeItem(itemId); + container.removePDP(pdp, newGroup); + } + + @Test(expected = UnsupportedOperationException.class) + public void testAddItem() { + container.addItem(); + } + + @Test(expected = UnsupportedOperationException.class) + public void testAddContainerProperty() { + container.addContainerProperty(null, null, null); + } - @Test(expected=UnsupportedOperationException.class) - public void testAddItem() { - container.addItem(); - } - - @Test(expected=UnsupportedOperationException.class) - public void testAddContainerProperty() { - container.addContainerProperty(null, null, null); - } + @Test(expected = UnsupportedOperationException.class) + public void testRemoveContainerProperty() { + container.removeContainerProperty(null); + } - @Test(expected=UnsupportedOperationException.class) - public void testRemoveContainerProperty() { - container.removeContainerProperty(null); - } + @Test(expected = UnsupportedOperationException.class) + public void testRemoveAllItems() { + container.removeAllItems(); + } - @Test(expected=UnsupportedOperationException.class) - public void testRemoveAllItems() { - container.removeAllItems(); - } + @Test(expected = UnsupportedOperationException.class) + public void testAddItemAfter() { + container.addItemAfter(null); + } - @Test(expected=UnsupportedOperationException.class) - public void testAddItemAfter() { - container.addItemAfter(null); - } - - @Test(expected=IndexOutOfBoundsException.class) - public void testGetIdByIndex() { - container.getIdByIndex(0); - } + @Test(expected = IndexOutOfBoundsException.class) + public void testGetIdByIndex() { + container.getIdByIndex(0); + } - @Test(expected=UnsupportedOperationException.class) - public void testAddItemAt() { - container.addItemAt(0); - } + @Test(expected = UnsupportedOperationException.class) + public void testAddItemAt() { + container.addItemAt(0); + } - @Test(expected=IllegalArgumentException.class) - public void testGetItemIds() { - container.getItemIds(0, 1); - } + @Test(expected = IllegalArgumentException.class) + public void testGetItemIds() { + container.getItemIds(0, 1); + } } |