diff options
Diffstat (limited to 'POLICY-SDK-APP/src/test/java/org/onap')
27 files changed, 2900 insertions, 628 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 deleted file mode 100644 index a06afc997..000000000 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.admin; - -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; - -@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/")); - - 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 - + "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/")); - - } 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/CheckPdpPropertiesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java new file mode 100644 index 000000000..afb6fc8b0 --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017, 2019 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.admin; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.att.research.xacml.util.XACMLProperties; +import java.io.File; +import java.io.IOException; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class CheckPdpPropertiesTest { + + @Test + public final void test1NoPropertySet() throws IOException { + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "noexistenfile.properties"); + assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/")); + + System.clearProperty(XACMLProperties.XACML_PROPERTIES_NAME); + System.clearProperty("xacml.rest.pdp.idfile"); + assertFalse(CheckPdpProperties.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(CheckPdpProperties.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(CheckPdpProperties.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(CheckPdpProperties.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(CheckPdpProperties.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(CheckPdpProperties.validateId("http://localhost:8082/pdp/")); + + assertNull(CheckPdpProperties.getPdpMap()); + assertNull(CheckPdpProperties.getEncoding("http://localhost:8082/pdp/")); + } + + @Test + public final void test2CheckPdp() throws IOException { + System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + "test.properties"); + assertTrue(CheckPdpProperties.validateId("http://localhost:8082/pdp/")); + assertTrue(CheckPdpProperties.getPdpMap().containsKey("http://localhost:8082/pdp/")); + assertTrue(CheckPdpProperties.getEncoding("http://localhost:8082/pdp/").equals("dGVzdHBkcDphbHBoYTQ1Ng==")); + } +} 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 7bd3be440..c3b98f525 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,22 +19,42 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; +import java.util.Date; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import javax.json.JsonArray; +import javax.script.SimpleBindings; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.commons.fileupload.FileItem; import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runners.MethodSorters; import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -49,10 +69,13 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.UserUtils.Pair; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.reflect.Whitebox; import org.springframework.mock.web.MockHttpServletResponse; +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PolicyManagerServletTest extends Mockito { private static Logger logger = FlexLogger.getLogger(PolicyManagerServletTest.class); @@ -67,6 +90,21 @@ public class PolicyManagerServletTest extends Mockito { private HttpServletRequest request; private MockHttpServletResponse response; + /** + * Delete test File. + * + */ + @AfterClass + public static void tearDown() { + File destroyFile = new File("testFileName.xls"); + destroyFile.deleteOnExit(); + } + + /** + * setUp. + * + * @throws Exception should not get one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); @@ -98,8 +136,7 @@ public class PolicyManagerServletTest extends Mockito { String policyContent = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils - .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -141,26 +178,22 @@ public class PolicyManagerServletTest extends Mockito { 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(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); commonClassDao = mock(CommonClassDao.class); } @Test - public void testInit() { + public void test01Init() { 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"); + 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"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "JSONConfig.json"); servlet.init(servletConfig); assertTrue(PolicyManagerServlet.getServiceTypeNamesList().size() > 0); @@ -173,18 +206,15 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testBadInitJson() { + public void test02BadInitJson() { 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"); + 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"); + 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); @@ -193,18 +223,15 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testBadInitJsonInvalidFile() { + public void test03BadInitJsonInvalidFile() { 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"); + 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"); + 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); @@ -214,11 +241,11 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void testDescribePolicy() { + public void test04DescribePolicy() { 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"; @@ -231,10 +258,9 @@ public class PolicyManagerServletTest extends Mockito { } } - @SuppressWarnings("static-access") @Test - public void testPolicyScopeList() { + public void test05PolicyScopeList() { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); @@ -245,14 +271,11 @@ public class PolicyManagerServletTest extends Mockito { try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("from PolicyEditorScopes", null)) + when(controller.getDataByQuery("from PolicyEditorScopes", null)).thenReturn(policyEditorScopes); + when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like :scopeName", 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); + when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like :scopeName", null)) + .thenReturn(policyVersion); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -265,20 +288,18 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editBasePolicyTest() { + public void test06editBasePolicyTest() { 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}}"); + 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); + 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); @@ -291,16 +312,16 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editBRMSParamPolicyTest() { + public void test07editBRMSParamPolicyTest() { 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")); + 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); } @@ -311,25 +332,22 @@ 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(); 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}}"); + 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); + 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); @@ -342,16 +360,16 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editBRMSRawPolicyTest() { + public void test08editBRMSRawPolicyTest() { 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")); + 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); } @@ -369,17 +387,15 @@ public class PolicyManagerServletTest extends Mockito { 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}}"); + 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); + 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); @@ -392,16 +408,16 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editClosedLoopFaultPolicyTest() { + public void test09editClosedLoopFaultPolicyTest() { 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")); + 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); } @@ -419,17 +435,15 @@ public class PolicyManagerServletTest extends Mockito { 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}}"); + 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); + 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); @@ -442,16 +456,15 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editClosedLoopPMPolicyTest() { + public void test10editClosedLoopPMPolicyTest() { 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")); + 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); } @@ -476,9 +489,8 @@ public class PolicyManagerServletTest extends Mockito { 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); + 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); @@ -491,7 +503,7 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editMicroServicePolicyTest() { + public void test11editMicroServicePolicyTest() { GroupPolicyScopeList groupData = new GroupPolicyScopeList(); groupData.setGroupName("Test"); groupData.setGroupList("resource=SampleResource,service=SampleService,type=SampleType," @@ -505,10 +517,8 @@ public class PolicyManagerServletTest extends Mockito { 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")); + 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); } @@ -526,20 +536,17 @@ public class PolicyManagerServletTest extends Mockito { 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}}"); + 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); + + "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); + 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); @@ -552,16 +559,14 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editFirewallPolicyTest() { + public void test12editFirewallPolicyTest() { 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")); + 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); } @@ -586,9 +591,8 @@ public class PolicyManagerServletTest extends Mockito { 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); + 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); @@ -601,16 +605,14 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editActionPolicyTest() { + public void test13editActionPolicyTest() { 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")); + 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); } @@ -626,16 +628,14 @@ public class PolicyManagerServletTest extends Mockito { 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}}"); + 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); + 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); @@ -648,13 +648,13 @@ public class PolicyManagerServletTest extends Mockito { @SuppressWarnings("static-access") @Test - public void editDecisionPolicyTest() { + public void test14editDecisionPolicyTest() { List<Object> policyData = new ArrayList<>(); String policyContent = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader - .getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); + policyContent = IOUtils + .toString(classLoader.getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -666,17 +666,15 @@ public class PolicyManagerServletTest extends Mockito { 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}}"); + 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); + 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); @@ -688,23 +686,20 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testAddScope() { + public void test15AddScope() { 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: '/', 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'}}"))); + 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")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -713,25 +708,23 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testClone() { + public void test16Clone() { 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'}}"))); + "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")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -740,25 +733,23 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testRename() { + public void test17Rename() { 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'}}"))); + "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")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -767,23 +758,402 @@ public class PolicyManagerServletTest extends Mockito { } @Test - public void testRenameScope() { + public void test18RenameScope() throws Exception { 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'}}"))); + 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")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); } } + + String inScopeName = "\\\\\\\\inScopeName"; + String newScopeName = "\\\\\\\\newScopeName"; + List<Object> scopesList = new ArrayList<Object>(); + PolicyEditorScopes mockPolicyEditorScope = Mockito.mock(PolicyEditorScopes.class); + scopesList.add(mockPolicyEditorScope); + when(mockPolicyEditorScope.getScopeName()).thenReturn("inScopeName"); + Whitebox.invokeMethod(servlet, "renameScope", scopesList, inScopeName, newScopeName, controller); + verify(mockPolicyEditorScope, atLeast(1)).getScopeName(); + } + + @Test + public void test19SetPolicyNames() { + JsonArray mockJsonArray = Mockito.mock(JsonArray.class); + PolicyManagerServlet.setPolicyNames(mockJsonArray); + assertEquals(mockJsonArray, PolicyManagerServlet.getPolicyNames()); + } + + @Test + public void test20DoPostSetErrorException() throws IOException { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + doThrow(IOException.class).when(mockRequest).getReader(); + doThrow(IOException.class).when(mockResponse).sendError(any(Integer.class), any(String.class)); + servlet.doPost(mockRequest, mockResponse); + verify(mockRequest).getReader(); + } + + @Test + public void test21DoPostException() throws IOException { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + + doThrow(IOException.class).when(mockRequest).getReader(); + doThrow(IOException.class).when(mockResponse).sendError(any(Integer.class), any(String.class)); + doThrow(IOException.class).when(mockResponse).getWriter(); + + servlet.doPost(mockRequest, mockResponse); + verify(mockRequest).getReader(); + verify(mockResponse).getWriter(); + } + + @Test + public void test22DoPostSuccess() throws IOException { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class); + + doThrow(IOException.class).when(mockRequest).getReader(); + when(mockResponse.getWriter()).thenReturn(mockPrintWriter); + + servlet.doPost(null, mockResponse); + verify(mockResponse).getWriter(); + } + + @Test + public void test23DoPostUploadFileException() { + PolicyManagerServlet servlet = new PolicyManagerServlet() { + private static final long serialVersionUID = 1L; + @Override + protected boolean isMultipartContent(HttpServletRequest request) { + return true; + } + }; + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + servlet.doPost(mockRequest, mockResponse); + } + + @Test + public void test24ProcessFormFile() throws Exception { + long fileSizeLimit = 10; + + PolicyManagerServlet servlet = new PolicyManagerServlet() { + private static final long serialVersionUID = 1L; + + @Override + protected long getFileSizeLimit() { + return fileSizeLimit; + } + + @Override + protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { + // don't really copy the file + return 0; + } + }; + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); + FileItem mockFileItem = Mockito.mock(FileItem.class); + InputStream mockInputStream = Mockito.mock(InputStream.class); + + when(mockFileItem.getName()).thenReturn("testFileName.xls"); + when(mockFileItem.getInputStream()).thenReturn(mockInputStream); + when(mockFileItem.getSize()).thenReturn(fileSizeLimit + 1); + + Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp); + verify(mockFileItem, atLeast(1)).getName(); + verify(mockFileItem, atLeast(1)).getSize(); + + when(mockFileItem.getName()).thenReturn("testFileName.txt"); + Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp); + verify(mockFileItem, atLeast(1)).getName(); + + when(mockFileItem.getSize()).thenReturn(fileSizeLimit); + when(mockFileItem.getName()).thenReturn("testFileName.xls"); + when(mockFileItem.getInputStream()).thenThrow(IOException.class); + Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp); + verify(mockFileItem, atLeast(1)).getName(); + verify(mockFileItem, atLeast(1)).getInputStream(); + verify(mockFileItem, atLeast(1)).getSize(); + } + + @Test + public void test25SearchPolicyList() throws Exception { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + JSONObject mockJSONObject = Mockito.mock(JSONObject.class); + + mockJSONObject.append("policyList", "sampleValue"); + + Object res = Whitebox.invokeMethod(servlet, "searchPolicyList", mockJSONObject, mockRequest); + assert (res instanceof JSONObject); + assertNotNull(((JSONObject) res).get("result")); + } + + @Test + public void test26LookupPolicyData() throws Exception { + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + User mockUser = Mockito.mock(User.class); + UserInfo mockUserInfo = Mockito.mock(UserInfo.class); + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + List<JSONObject> resultList = new ArrayList<>(); + JSONObject mockJSONObject = Mockito.mock(JSONObject.class); + resultList.add(mockJSONObject); + + Date mockDate = Mockito.mock(Date.class); + List<Object> policyDataList = new ArrayList<>(); + PolicyVersion mockPolicyVersion = Mockito.mock(PolicyVersion.class); + policyDataList.add(mockPolicyVersion); + JSONArray mockJSONArray = Mockito.mock(JSONArray.class); + + List<Object> rolesList = new ArrayList<>(); + Roles adminRole = Mockito.mock(Roles.class); + Roles editorRole = Mockito.mock(Roles.class); + Roles guestRole = Mockito.mock(Roles.class); + adminRole.setRole("admin"); + editorRole.setRole("editor"); + guestRole.setRole("guest"); + + List<Object> filterDataList = new ArrayList<>(); + PolicyVersion mockPolicyVersionFilter = Mockito.mock(PolicyVersion.class); + filterDataList.add(mockPolicyVersionFilter); + List<String> listOfRoles = new ArrayList<String>(); + Set<String> setOfScopes = new HashSet<String>(); + Pair<Set<String>, List<String>> pairList = new Pair<Set<String>, List<String>>(setOfScopes, listOfRoles); + + PolicyManagerServlet servlet = new PolicyManagerServlet() { + private static final long serialVersionUID = 1L; + + @Override + protected User getUserSession(HttpServletRequest request) { + return mockUser; + } + + @Override + protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) { + return pairList; + } + }; + + PolicyManagerServlet.setPolicyController(mockPolicyController); + when(mockPolicyController.getRoles(any(String.class))).thenReturn(rolesList); + when(mockPolicyController.getData(any(Class.class))).thenReturn(filterDataList); + when(mockPolicyVersion.getPolicyName()).thenReturn("sampleName"); + when(mockPolicyVersion.getModifiedDate()).thenReturn(mockDate); + when(mockPolicyVersion.getActiveVersion()).thenReturn(1); + when(mockPolicyVersion.getCreatedBy()).thenReturn("sampleUserName"); + when(mockPolicyVersion.getModifiedBy()).thenReturn("sampleUserName"); + when(mockPolicyController.getEntityItem(UserInfo.class, "userLoginId", "sampleUserName")) + .thenReturn(mockUserInfo); + when(mockUserInfo.getUserName()).thenReturn("testUserName"); + + Whitebox.invokeMethod(servlet, "getPolicyControllerInstance"); + + boolean result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null, + mockPolicyController, resultList); + + assertTrue(result); + verify(mockPolicyController, atLeast(1)).getRoles(any()); + verify(mockPolicyController, atLeast(1)).getRoles(any()); + verify(mockPolicyController, atLeast(1)).getData(any()); + verify(mockPolicyController, atLeast(1)).getEntityItem(UserInfo.class, "userLoginId", "sampleUserName"); + verify(mockPolicyVersion, atLeast(1)).getPolicyName(); + verify(mockPolicyVersion, atLeast(1)).getModifiedDate(); + verify(mockPolicyVersion, atLeast(1)).getActiveVersion(); + verify(mockPolicyVersion, atLeast(1)).getCreatedBy(); + verify(mockPolicyVersion, atLeast(1)).getModifiedBy(); + verify(mockUserInfo, atLeast(1)).getUserName(); + + when(mockPolicyVersionFilter.getPolicyName()).thenReturn("testAdminScope" + File.separator); + result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null, + mockPolicyController, resultList); + assertTrue(result); + verify(mockPolicyVersionFilter, atLeast(1)).getPolicyName(); + + setOfScopes.add("testAdminScope"); + result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null, + mockPolicyController, resultList); + assertTrue(result); + verify(mockPolicyVersionFilter, atLeast(1)).getPolicyName(); + + listOfRoles.add("super-admin"); + listOfRoles.add("super-editor"); + listOfRoles.add("super-guest"); + filterDataList.clear(); + + result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null, + mockPolicyController, resultList); + assertTrue(result); + verify(mockPolicyController, atLeast(1)).getData(any(Class.class)); + + listOfRoles.clear(); + listOfRoles.add("admin"); + listOfRoles.add("editor"); + listOfRoles.add("guest"); + setOfScopes.clear(); + result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null, + mockPolicyController, resultList); + assertFalse(result); + + setOfScopes.add("testScope"); + result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, mockJSONArray, + mockPolicyController, resultList); + assertTrue(result); + } + + @Test + public void test27DeleteEntityFromEsAndPolicyEntityTable() throws Exception { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + PolicyRestController mockPolicyRestController = Mockito.mock(PolicyRestController.class); + PolicyEntity mockPolicyEntity = Mockito.mock(PolicyEntity.class); + ConfigurationDataEntity mockConfigDataEntity = Mockito.mock(ConfigurationDataEntity.class); + ActionBodyEntity mockActionBodyEntity = Mockito.mock(ActionBodyEntity.class); + + String policyNamewithoutExtension = "Config_"; + String configName = ""; + String actionBodyName = ""; + + when(mockPolicyEntity.getScope()).thenReturn(""); + when(mockPolicyEntity.getPolicyName()).thenReturn(""); + Mockito.doNothing().when(mockPolicyRestController).deleteElasticData(any(String.class)); + Mockito.doNothing().when(mockPolicyController).deleteData(mockPolicyEntity); + when(mockPolicyEntity.getConfigurationData()).thenReturn(mockConfigDataEntity); + when(mockPolicyEntity.getActionBodyEntity()).thenReturn(mockActionBodyEntity); + when(mockConfigDataEntity.getConfigurationName()).thenReturn(configName); + when(mockActionBodyEntity.getActionBodyName()).thenReturn(actionBodyName); + when(mockPolicyRestController.notifyOtherPapsToUpdateConfigurations("delete", null, configName)).thenReturn(""); + + Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController, + mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension); + + verify(mockPolicyEntity, atLeast(1)).getScope(); + verify(mockPolicyEntity, atLeast(1)).getPolicyName(); + verify(mockPolicyEntity, atLeast(1)).getConfigurationData(); + verify(mockConfigDataEntity, atLeast(1)).getConfigurationName(); + + policyNamewithoutExtension = "Action_"; + when(mockPolicyRestController.notifyOtherPapsToUpdateConfigurations("delete", null, actionBodyName)) + .thenReturn(""); + + Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController, + mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension); + + verify(mockPolicyEntity, atLeast(1)).getScope(); + verify(mockPolicyEntity, atLeast(1)).getPolicyName(); + verify(mockPolicyEntity, atLeast(1)).getActionBodyEntity(); + verify(mockActionBodyEntity, atLeast(1)).getActionBodyName(); + + policyNamewithoutExtension = "Other_"; + Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController, + mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension); + + verify(mockPolicyEntity, atLeast(1)).getScope(); + verify(mockPolicyEntity, atLeast(1)).getPolicyName(); + verify(mockPolicyRestController, atLeast(1)).deleteElasticData(any(String.class)); + verify(mockPolicyController, atLeast(1)).deleteData(mockPolicyEntity); + } + + @Test + public void test28Delete() throws Exception { + JSONObject mockJSONObject = Mockito.mock(JSONObject.class); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + User mockUser = Mockito.mock(User.class); + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + List<Object> policyEntityList = new ArrayList<Object>(); + PolicyEntity mockPolicyEntity = Mockito.mock(PolicyEntity.class); + policyEntityList.add(mockPolicyEntity); + long policyId = 1; + + PolicyManagerServlet servlet = new PolicyManagerServlet() { + private static final long serialVersionUID = 1L; + + @Override + protected User getUserSession(HttpServletRequest request) { + return mockUser; + } + }; + + PolicyManagerServlet.setPolicyController(mockPolicyController); + when(mockUser.getOrgUserId()).thenReturn("sampleUserId"); + when(mockJSONObject.getString("path")).thenReturn("/sampleScope:samplePolicyName.1.xml"); + when(mockJSONObject.has("deleteVersion")).thenReturn(true); + when(mockJSONObject.getString("deleteVersion")).thenReturn("ALL"); + when(mockPolicyController.getDataByQuery(any(String.class), any(SimpleBindings.class))) + .thenReturn(policyEntityList); + when(mockPolicyEntity.getPolicyId()).thenReturn(policyId); + when(mockPolicyEntity.getScope()).thenReturn("sampleScope"); + when(mockPolicyEntity.getPolicyName()).thenReturn("samplePolicyName"); + + JSONObject returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest); + assertTrue(returnObj.has("result")); + verify(mockUser, atLeast(1)).getOrgUserId(); + verify(mockJSONObject, atLeast(1)).getString(any(String.class)); + verify(mockJSONObject, atLeast(1)).has(any(String.class)); + verify(mockPolicyController, atLeast(1)).getDataByQuery(any(String.class), any(SimpleBindings.class)); + verify(mockPolicyEntity, atLeast(1)).getPolicyId(); + verify(mockPolicyEntity, atLeast(1)).getScope(); + verify(mockPolicyEntity, atLeast(1)).getPolicyName(); + + when(mockJSONObject.getString("path")).thenReturn("/sampleScope\\:samplePolicyName.1.xml"); + when(mockJSONObject.getString("deleteVersion")).thenReturn("CURRENT"); + returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest); + assertTrue(returnObj.has("result")); + verify(mockJSONObject, atLeast(1)).getString(any(String.class)); + + when(mockJSONObject.getString("path")).thenReturn("/sampleScope:samplePolicyName.2.txt"); + when(mockJSONObject.has("deleteVersion")).thenReturn(false); + returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest); + assertTrue(returnObj.has("result")); + verify(mockJSONObject, atLeast(1)).getString("path"); + verify(mockJSONObject, atLeast(1)).has("deleteVersion"); + } + + @Test + public void test29ParsePolicyList() throws Exception { + PolicyManagerServlet servlet = new PolicyManagerServlet(); + List<JSONObject> resultList = new ArrayList<JSONObject>(); + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + UserInfo mockUserInfo = Mockito.mock(UserInfo.class); + String policyName = "sampleName\\"; + String policyVersion = "sampleVersion"; + List<Object> activeDataList = new ArrayList<Object>(); + PolicyVersion mockPolicyVersion = Mockito.mock(PolicyVersion.class); + activeDataList.add(mockPolicyVersion); + Date mockDate = Mockito.mock(Date.class); + + when(mockPolicyController.getDataByQuery(any(String.class), any(SimpleBindings.class))) + .thenReturn(activeDataList); + when(mockPolicyVersion.getPolicyName()).thenReturn("testPolicyName"); + when(mockPolicyVersion.getModifiedDate()).thenReturn(mockDate); + when(mockPolicyVersion.getActiveVersion()).thenReturn(1); + when(mockPolicyVersion.getCreatedBy()).thenReturn("sampleUserName"); + when(mockPolicyVersion.getModifiedBy()).thenReturn("sampleUserName"); + // + // This intermittently throws an NPE, even when fixing the method order + // + when(mockPolicyController.getEntityItem(UserInfo.class, "userLoginId", "sampleUserName")) + .thenReturn(mockUserInfo); + when(mockUserInfo.getUserName()).thenReturn("testUserName"); + Whitebox.invokeMethod(servlet, "parsePolicyList", resultList, mockPolicyController, policyName, policyVersion); + verify(mockPolicyController, atLeast(1)).getDataByQuery(any(String.class), any(SimpleBindings.class)); + verify(mockPolicyVersion, atLeast(1)).getPolicyName(); + verify(mockPolicyVersion, atLeast(1)).getModifiedDate(); + verify(mockPolicyVersion, atLeast(1)).getActiveVersion(); + verify(mockPolicyVersion, atLeast(1)).getCreatedBy(); + verify(mockPolicyVersion, atLeast(1)).getModifiedBy(); } } 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 95296f4b0..5111ef2a8 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,16 +19,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; 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 org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.when; +import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.controller.PolicyController; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyVersion; @@ -41,16 +45,27 @@ public class PolicyNotificationMailTest { private CommonClassDao commonClassDao; private List<Object> data = null; + /** + * setUp. + * + * @throws Exception should not throw one + */ @Before public void setUp() throws Exception { PolicyController.setjUnit(true); PolicyController.setSmtpApplicationName("Test"); PolicyController.setSmtpEmailExtension("test.com"); - PolicyController.setSmtpHost("test"); - PolicyController.setSmtpPort("23"); + PolicyController.setSmtpHost("localhost"); PolicyController.setSmtpPassword("test"); PolicyController.setSmtpUsername("test"); + /* + * Allocate a port to which the mail sender should connect, but don't actually + * start a listener on the port so that connection attempts will be immediately + * rejected. + */ + PolicyController.setSmtpPort(String.valueOf(NetworkUtil.allocPort())); + version = new PolicyVersion(); version.setPolicyName("com/Config_Test"); version.setModifiedBy("xyz"); @@ -62,9 +77,8 @@ public class PolicyNotificationMailTest { commonClassDao = mock(CommonClassDao.class); PolicyController.setCommonClassDao(commonClassDao); - when(commonClassDao.getDataByQuery( - "from WatchPolicyNotificationTable where policyName like:policyFileName", null)) - .thenReturn(data); + when(commonClassDao.getDataByQuery("from WatchPolicyNotificationTable where policyName like:policyFileName", + null)).thenReturn(data); } @Test 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 ce38f236f..6c47b3955 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,26 +19,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; import java.io.StringReader; +import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.policy.controller.CreateFirewallController; +import org.onap.policy.controller.PolicyController; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.AddressGroup; -import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.FwTagPicker; import org.onap.policy.rest.jpa.GroupServiceList; import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.SecurityZone; @@ -46,8 +60,16 @@ import org.onap.policy.rest.jpa.ServiceList; import org.onap.policy.rest.jpa.TermList; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; import org.springframework.mock.web.MockHttpServletResponse; +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "com.sun.org.apache.xalan.*"}) public class PolicyRestControllerTest { private String clRequestString; @@ -65,77 +87,78 @@ public class PolicyRestControllerTest { private List<Object> tagListData; private List<Object> termListData; + /** + * Before. + * + * @throws Exception exception + */ @Before public void setUp() throws Exception { commonClassDao = mock(CommonClassDao.class); - HttpSession mockSession = mock(HttpSession.class); + final 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(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\"}}}"; + 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\":" @@ -144,8 +167,6 @@ public class PolicyRestControllerTest { + "\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\",\"guard\":\"True\"," + "\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}"; - - prefixListData = new ArrayList<>(); PrefixList prefixList = new PrefixList(); prefixList.setPrefixListName("Test"); @@ -163,7 +184,7 @@ public class PolicyRestControllerTest { ServiceList serviceList = new ServiceList(); serviceList.setServiceName("Test"); serviceList.setServiceType("SERVICE"); - serviceList.setServiceTransProtocol("Test"); + serviceList.setServiceTransportProtocol("Test"); serviceList.setServiceAppProtocol("Test"); serviceList.setServicePorts("8080"); serviceListData.add(serviceList); @@ -191,30 +212,33 @@ public class PolicyRestControllerTest { when(commonClassDao.getData(GroupServiceList.class)).thenReturn(serviceGroupData); tagListData = new ArrayList<>(); - FWTagPicker fwPicker = new FWTagPicker(); + FwTagPicker fwPicker = new FwTagPicker(); fwPicker.setTagPickerName("Test"); fwPicker.setTagValues("Test:8080"); tagListData.add(fwPicker); - when(commonClassDao.getData(FWTagPicker.class)).thenReturn(tagListData); + 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.setFromZone("Test"); + termList.setToZone("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); + when(commonClassDao.getDataById(TermList.class, "termName", "Test")).thenReturn(termListData); } @Test public final void testPolicyCreationController() { + assertNull(PolicyRestController.getCommonClassDao()); + PolicyRestController.setCommonClassDao(commonClassDao); + assertNotNull(PolicyRestController.getCommonClassDao()); + PolicyRestController controller = new PolicyRestController(); BufferedReader reader = new BufferedReader(new StringReader(clRequestString)); try { @@ -225,6 +249,7 @@ public class PolicyRestControllerTest { } PolicyRestController controller1 = new PolicyRestController(); CreateFirewallController.setCommonClassDao(commonClassDao); + assertNotNull(CreateFirewallController.getCommonClassDao()); BufferedReader reader1 = new BufferedReader(new StringReader(fwRequestString)); try { Mockito.when(request.getReader()).thenReturn(reader1); @@ -245,6 +270,27 @@ public class PolicyRestControllerTest { } @Test + public final void testSearchPolicy() throws IOException { + PolicyController.setjUnit(true); + PolicyController.setPapUrl("http://localhost:8070/pap/"); + PolicyRestController controller = new PolicyRestController(); + BufferedReader reader = new BufferedReader(new StringReader("{\"foo\":\"bar\"}")); + Mockito.when(request.getReader()).thenReturn(reader); + Mockito.when(request.getRequestURI()).thenReturn("/pap/foo/"); + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy(() -> controller.searchPolicy(request, response)); + } + + @Test + public final void testSearchDictionaryController() throws IOException { + PolicyRestController controller = new PolicyRestController(); + BufferedReader reader = new BufferedReader(new StringReader("{\"foo\":\"bar\"}")); + Mockito.when(request.getReader()).thenReturn(reader); + Mockito.when(request.getRequestURI()).thenReturn("/pap/foo/"); + assertNull(controller.searchDictionaryController(request, response)); + } + + @Test public final void testDeleteElasticData() { PolicyRestController controller = new PolicyRestController(); try { @@ -253,4 +299,101 @@ public class PolicyRestControllerTest { fail(); } } + + @Test + public final void testNotifyOtherPaps() { + PolicyRestController controller = new PolicyRestController(); + String strReturn = controller.notifyOtherPapsToUpdateConfigurations("mode", "newName", "oldName"); + assertNull(strReturn); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetDictionaryController() throws IOException { + PolicyRestController controller = new PolicyRestController(); + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class); + + when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///getDictionary"); + when(mockResponse.getWriter()).thenThrow(IOException.class); + controller.getDictionaryController(mockRequest, mockResponse); + verify(mockRequest, atLeast(1)).getRequestURI(); + verify(mockResponse, atLeast(1)).getWriter(); + + reset(mockResponse); + when(mockRequest.getRequestURI()).thenReturn("testRequestURI///getDictionary"); + when(mockResponse.getWriter()).thenReturn(mockPrintWriter); + controller.getDictionaryController(mockRequest, mockResponse); + verify(mockRequest, atLeast(1)).getRequestURI(); + verify(mockResponse, atLeast(1)).getWriter(); + } + + @PrepareForTest(UserUtils.class) + @Test + public void testdeletetDictionaryController() throws IOException { + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + PolicyRestController controller = new PolicyRestController(); + User mockUser = Mockito.mock(User.class); + PowerMockito.mockStatic(UserUtils.class); + PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class); + + when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///deleteDictionary"); + when(mockResponse.getWriter()).thenReturn(mockPrintWriter); + when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser); + when(mockUser.getOrgUserId()).thenReturn("testUserId"); + + controller.deletetDictionaryController(mockRequest, mockResponse); + verify(mockRequest).getRequestURI(); + verify(mockResponse).getWriter(); + verify(mockUser).getOrgUserId(); + + when(mockRequest.getRequestURI()).thenReturn("testRequestURI///deleteDictionary"); + controller.deletetDictionaryController(mockRequest, mockResponse); + verify(mockRequest, atLeast(1)).getRequestURI(); + } + + @PrepareForTest(UserUtils.class) + @Test + public void testSaveDictionaryController() throws IOException { + HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + PolicyRestController controller = new PolicyRestController(); + User mockUser = Mockito.mock(User.class); + PowerMockito.mockStatic(UserUtils.class); + PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class); + + when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///saveDictionary//import_dictionary"); + when(mockResponse.getWriter()).thenReturn(mockPrintWriter); + when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser); + when(mockUser.getOrgUserId()).thenReturn("testUserId"); + + controller.saveDictionaryController(mockRequest, mockResponse); + verify(mockRequest).getRequestURI(); + verify(mockResponse).getWriter(); + verify(mockUser).getOrgUserId(); + + when(mockRequest.getRequestURI()).thenReturn("testRequestURI///saveDictionary"); + controller.saveDictionaryController(mockRequest, mockResponse); + verify(mockRequest, atLeast(1)).getRequestURI(); + } + + @Test + public void testDoConnect() throws Exception { + HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class); + PolicyRestController controller = new PolicyRestController(); + Mockito.doNothing().when(mockConnection).connect(); + InputStream mockInputStream = Mockito.mock(InputStream.class); + + when(mockConnection.getResponseCode()).thenReturn(200); + when(mockConnection.getInputStream()).thenReturn(mockInputStream); + + Whitebox.invokeMethod(controller, "doConnect", mockConnection); + verify(mockConnection).getResponseCode(); + verify(mockConnection).getInputStream(); + + when(mockConnection.getResponseCode()).thenReturn(201); + assertNull(Whitebox.invokeMethod(controller, "doConnect", mockConnection)); + } } 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 d05b7933d..55e4b5a93 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,12 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Test; @@ -45,8 +52,7 @@ public class PolicyUserInfoControllerTest { response = new MockHttpServletResponse(); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); } @@ -60,4 +66,14 @@ public class PolicyUserInfoControllerTest { fail(); } } + + @SuppressWarnings("unchecked") + @Test + public void testGetPolicyUserInfoException() throws IOException { + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + when(mockResponse.getWriter()).thenThrow(IOException.class); + PolicyUserInfoController controller = new PolicyUserInfoController(); + controller.getPolicyUserInfo(request, mockResponse); + verify(mockResponse, atLeast(1)).getWriter(); + } } 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 4b307f594..0deb3d6fc 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,35 +19,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertNull; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; -import java.net.URL; -import javax.servlet.http.HttpServletResponse; import java.net.HttpURLConnection; -import org.junit.Before; -import org.junit.Rule; +import java.net.URLConnection; +import javax.servlet.http.HttpServletResponse; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import com.att.research.xacml.api.pap.PAPException; -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"; @@ -56,28 +51,55 @@ public class RESTfulPAPEngineTest { private String policyType = "testType"; private String policyContent = "testContent"; private int jmxport = 0; + private String userId = "testId"; 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); + /** + * BeforeClass does some simple code coverage and sets up the + * XACML properties. + */ + @BeforeClass + public static void setUpBeforeClass() { + // + // Test constructor with bad URL + // + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + new RESTfulPAPEngine(null)); + + XACMLProperties.reloadProperties(); + } + + @AfterClass + public static void tearDownAfterClass() { + XACMLProperties.reloadProperties(); + } + + private void setupConnection(int responseCode, String location) throws Exception { + // Mock connection HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); - Mockito.when(url.openConnection()).thenReturn(connection); - Mockito.when(connection.getResponseCode()).thenReturn(HttpServletResponse.SC_NO_CONTENT); + + Mockito.when(connection.getResponseCode()).thenReturn(responseCode); + Mockito.when(connection.getHeaderField("Location")).thenReturn(location); + + InputStream mockInputStream = Mockito.mock(InputStream.class); + Mockito.when(connection.getInputStream()).thenReturn(mockInputStream); // Set the system property temporarily String systemKey = "xacml.properties"; - String oldProperty = System.getProperty(systemKey); + final String oldProperty = System.getProperty(systemKey); System.setProperty(systemKey, "src/test/resources/xacml.admin.properties"); // Test constructor String urlName = "localhost:1234"; - engine = new RESTfulPAPEngine(urlName); + engine = new RESTfulPAPEngine(urlName) { + @Override + protected URLConnection makeConnection(String fullUrl) throws IOException { + return connection; + } + }; // Initialize policy policy = new ByteArrayInputStream(policyContent.getBytes("UTF-8")); @@ -91,75 +113,89 @@ public class RESTfulPAPEngineTest { } @Test - public void testGroups() throws Exception { + public void testAllTheExceptions() throws Exception { + setupConnection(HttpServletResponse.SC_NO_CONTENT, "localhost:5678"); + engine.setDefaultGroup(group); - assertEquals(engine.getDefaultGroup(), null); + assertNull(engine.getDefaultGroup()); 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."); - } + assertNull(engine.getPDPGroup(pdp)); + assertNull(engine.getPDPGroup(id)); + assertNull(engine.getPDP(id)); + assertNull(engine.getStatus(pdp)); - @Test - public void testUpdateGroup() throws PAPException { - thrown.expect(PAPException.class); - engine.updateGroup(group); - fail("Expecting an exception."); - } + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> + engine.getOnapPDPGroups() + ); - @Test - public void testPDP() throws PAPException { - assertEquals(engine.getGroup(name), null); - engine.movePDP(pdp, newGroup); + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.updateGroup(group) + ); - thrown.expect(PAPException.class); - engine.newPDP(id, newGroup, name, description, jmxport); - fail("Expecting an exception."); - } + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.updateGroup(group, "testUserName") + ); - @Test - public void testUpdatePDP() throws PAPException { - thrown.expect(NullPointerException.class); - engine.updatePDP(pdp); - fail("Expecting an exception."); - } + assertNull(engine.getGroup(name)); + engine.movePDP(pdp, newGroup); - @Test - public void testRemovePDP() throws PAPException { - thrown.expect(NullPointerException.class); - engine.removePDP(pdp); - fail("Expecting an exception."); - } + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.newPDP(id, newGroup, name, description, jmxport) + ); - @Test - public void testValidatePolicy() throws PAPException { - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> + engine.updatePDP(pdp) + ); - thrown.expect(PAPException.class); - engine.validatePolicyRequest(policyAdapter, policyType); - fail("Expecting an exception."); - } + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> + engine.removePDP(pdp) + ); - @Test - public void testPublishPolicy() throws PAPException { - thrown.expect(PAPException.class); - engine.publishPolicy(id, name, false, policy, newGroup); - fail("Expecting an exception."); - } + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.validatePolicyRequest(new PolicyRestAdapter(), policyType) + ); - @Test - public void testCopy() throws PAPException { - engine.copyFile(id, newGroup, policy); - PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class); + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.publishPolicy(id, name, false, policy, newGroup) + ); - thrown.expect(PAPException.class); - engine.copyPolicy(pdpPolicy, newGroup); - fail("Expecting an exception."); + engine.copyFile(id, newGroup, policy, userId); + PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class); + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.copyPolicy(pdpPolicy, newGroup, userId) + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.removePolicy(null, group) + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + engine.copyPolicy(null, null, null) + ); + + // + // Change the mockito to take a different path + // + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + setupConnection(HttpServletResponse.SC_FOUND, "localhost:5678") + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + setupConnection(200, "localhost:5678") + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + setupConnection(350, "localhost:5678") + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + setupConnection(500, "localhost:5678") + ); + + assertThatExceptionOfType(PAPException.class).isThrownBy(() -> + setupConnection(350, null) + ); } + } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java new file mode 100644 index 000000000..b56d3fd94 --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java @@ -0,0 +1,839 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.XACML1; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.xml.bind.JAXBElement; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +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.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; + +public class HumanPolicyComponentTest { + + private AttributeIdentifiers attrIds; + private HtmlProcessor processor; + private static File temp; + private static File tempAction; + private static File tempConfig; + + @BeforeClass + public static void setup() throws IOException { + temp = File.createTempFile("tmpFile", ".tmp"); + tempAction = File.createTempFile("Action_test", ".tmp"); + tempConfig = File.createTempFile("Config_test", ".tmp"); + temp.deleteOnExit(); + tempAction.deleteOnExit(); + tempConfig.deleteOnExit(); + } + + @Test + public void testAttributeIdentifiers() { + String testCategory = "testCategory"; + String testID = "testId"; + String testType = "testType"; + String newTestType = "testNewType"; + + attrIds = new AttributeIdentifiers(testCategory, testType, testID); + assertEquals(testCategory, attrIds.category); + assertEquals(testID, attrIds.id); + assertEquals(testType, attrIds.getType()); + + attrIds.setType(newTestType); + assertEquals(newTestType, attrIds.getType()); + } + + @SuppressWarnings("unchecked") + @Test + public void testHumanPolicyComponentException() { + JAXBElement<PolicySetType> mockRoot = Mockito.mock(JAXBElement.class); + when(mockRoot.getValue()).thenReturn(null); + assertNull(HumanPolicyComponent.DescribePolicy(temp)); + } + + @Test(expected = IllegalArgumentException.class) + public void testHtmlProcessorNull() throws IOException { + processor = new HtmlProcessor(null, null); + } + + @Test(expected = IllegalArgumentException.class) + public void testHtmlProcessor() throws IOException { + File tempFile = File.createTempFile("testFile", ".tmp"); + tempFile.delete(); + processor = new HtmlProcessor(tempFile, null); + } + + @Test(expected = IllegalArgumentException.class) + public void testHtmlProcessorInvalidObject() throws IOException { + processor = new HtmlProcessor(temp, null); + } + + @Test + public void testHtmlProcessorConfigPolicySetType() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(tempConfig, mockPolicySetType); + processor.onFinishScan(mockPolicySetType); + verify(mockPolicySetType).getVersion(); + } + + @Test + public void testHtmlProcessorActionPolicySetType() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(tempAction, mockPolicySetType); + processor.onFinishScan(mockPolicySetType); + verify(mockPolicySetType).getVersion(); + } + + @Test + public void testHtmlProcessorConfigPolicyType() { + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + processor = new HtmlProcessor(tempConfig, mockPolicyType); + verify(mockPolicyType).getVersion(); + } + + @Test + public void testHtmlProcessorActionPolicyType() { + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + processor = new HtmlProcessor(tempAction, mockPolicyType); + assertNotNull(processor.getAttributeIdentifiersMap()); + verify(mockPolicyType).getVersion(); + } + + @Test + public void testHtmlProcessorOnPreVisitPolicySet() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicySetType mockPolicyParent = Mockito.mock(PolicySetType.class); + + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(Collections.emptyList()); + when(mockPolicySetType.getDescription()).thenReturn(null); + + CallbackResult preResult = processor.onPreVisitPolicySet(mockPolicyParent, mockPolicySetType); + assertEquals("CONTINUE", preResult.name()); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + verify(mockPolicySetType, atLeast(1)).getDescription(); + } + + @Test + public void testHtmlProcessorOnPreVisitPolicySetNullParent() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicySetType mockPolicyParent = null; + JAXBElement<?> mockElement = Mockito.mock(JAXBElement.class); + + List<JAXBElement<?>> testList = new ArrayList<JAXBElement<?>>(); + testList.add(mockElement); + + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(testList); + when(mockPolicySetType.getDescription()).thenReturn(""); + + CallbackResult preResult = processor.onPreVisitPolicySet(mockPolicyParent, mockPolicySetType); + assertEquals("CONTINUE", preResult.name()); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + verify(mockPolicySetType, atLeast(1)).getDescription(); + } + + @Test + public void testHtmlProcessorOnPostVisitPolicySet() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicySetType mockPolicyParent = Mockito.mock(PolicySetType.class); + + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(Collections.emptyList()); + when(mockPolicySetType.getDescription()).thenReturn(null); + + CallbackResult postResult = processor.onPostVisitPolicySet(mockPolicyParent, mockPolicySetType); + assertEquals("CONTINUE", postResult.name()); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + verify(mockPolicySetType, atLeast(1)).getDescription(); + } + + @Test + public void testHtmlProcessorOnPostVisitPolicySetNullParent() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicySetType mockPolicyParent = null; + JAXBElement<?> mockElement = Mockito.mock(JAXBElement.class); + + List<JAXBElement<?>> testList = new ArrayList<JAXBElement<?>>(); + testList.add(mockElement); + + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(testList); + when(mockPolicySetType.getDescription()).thenReturn(""); + + CallbackResult postResult = processor.onPostVisitPolicySet(mockPolicyParent, mockPolicySetType); + assertEquals("CONTINUE", postResult.name()); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + verify(mockPolicySetType, atLeast(1)).getDescription(); + } + + @Test + public void testHtmlProcessorOnPreVisitPolicy() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + List<Object> testList = new ArrayList<Object>(); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList); + when(mockPolicySetType.getDescription()).thenReturn(null); + + CallbackResult preResult = processor.onPreVisitPolicy(mockPolicySetType, mockPolicyType); + assertEquals("CONTINUE", preResult.name()); + verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + verify(mockPolicyType, atLeast(1)).getDescription(); + } + + @Test + public void testHtmlProcessorOnPreVisitPolicyNullParent() { + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + PolicySetType mockPolicyParent = null; + List<Object> testList = new ArrayList<Object>(); + testList.add(new Object()); + processor = new HtmlProcessor(temp, mockPolicyType); + + when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList); + when(mockPolicyType.getDescription()).thenReturn(""); + + CallbackResult preResult = processor.onPreVisitPolicy(mockPolicyParent, mockPolicyType); + assertEquals("CONTINUE", preResult.name()); + verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + verify(mockPolicyType, atLeast(1)).getDescription(); + + } + + @Test + public void testHtmlProcessorOnPostVisitPolicy() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + List<Object> testList = new ArrayList<Object>(); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList); + + CallbackResult postResult = processor.onPostVisitPolicy(mockPolicySetType, mockPolicyType); + assertEquals("CONTINUE", postResult.name()); + verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + } + + @Test + public void testHtmlProcessorOnPostVisitPolicyNullParent() { + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + PolicySetType mockPolicyParent = null; + List<Object> testList = new ArrayList<Object>(); + testList.add(new Object()); + processor = new HtmlProcessor(temp, mockPolicyType); + + when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList); + + CallbackResult postResult = processor.onPostVisitPolicy(mockPolicyParent, mockPolicyType); + assertEquals("CONTINUE", postResult.name()); + verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + } + + @Test + public void testHtmlProcessorPolicy() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null); + when(mockPolicyType.getPolicyId()).thenReturn(null); + when(mockPolicyType.getVersion()).thenReturn(null); + when(mockPolicyType.getTarget()).thenReturn(null); + + processor.policy(mockPolicyType); + verify(mockPolicyType).getRuleCombiningAlgId(); + verify(mockPolicyType).getPolicyId(); + verify(mockPolicyType).getVersion(); + verify(mockPolicyType).getTarget(); + } + + @Test + public void testHtmlProcessorPolicyListEmpty() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null); + when(mockPolicyType.getPolicyId()).thenReturn(null); + when(mockPolicyType.getVersion()).thenReturn(null); + when(mockPolicyType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + + processor.policy(mockPolicyType); + + verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId(); + verify(mockPolicyType, atLeast(1)).getPolicyId(); + verify(mockPolicyType, atLeast(1)).getVersion(); + verify(mockPolicyType, atLeast(1)).getTarget(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + } + + @Test + public void testHtmlProcessorPolicyListNotEmpty() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + anyOfList.add(new AnyOfType()); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null); + when(mockPolicyType.getPolicyId()).thenReturn(null); + when(mockPolicyType.getVersion()).thenReturn(null); + when(mockPolicyType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + + processor.policy(mockPolicyType); + verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId(); + verify(mockPolicyType, atLeast(1)).getPolicyId(); + verify(mockPolicyType, atLeast(1)).getVersion(); + verify(mockPolicyType, atLeast(1)).getTarget(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + } + + @Test + public void testHtmlProcessorPolicyNull() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = Mockito.mock(PolicyType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null); + when(mockPolicyType.getPolicyId()).thenReturn(null); + when(mockPolicyType.getVersion()).thenReturn(null); + when(mockPolicyType.getTarget()).thenReturn(mockTargetType); + when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(null); + when(mockTargetType.getAnyOf()).thenReturn(null); + + processor.policy(mockPolicyType); + verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId(); + verify(mockPolicyType, atLeast(1)).getPolicyId(); + verify(mockPolicyType, atLeast(1)).getVersion(); + verify(mockPolicyType, atLeast(1)).getTarget(); + verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + } + + @Test + public void testHtmlProcessorPolicySet() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getPolicyCombiningAlgId()).thenReturn(""); + when(mockPolicySetType.getPolicySetId()).thenReturn(""); + when(mockPolicySetType.getVersion()).thenReturn(""); + + processor.policySet(mockPolicySetType, ""); + verify(mockPolicySetType, atLeast(1)).getPolicyCombiningAlgId(); + verify(mockPolicySetType, atLeast(1)).getPolicySetId(); + verify(mockPolicySetType, atLeast(1)).getVersion(); + } + + @Test + public void testHtmlProcessorPolicySetNull() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(null); + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null); + + processor.policySet(mockPolicySetType, ""); + verify(mockPolicySetType, atLeast(1)).getTarget(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + } + + @Test + public void testHtmlProcessorPolicySetEmpty() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + processor = new HtmlProcessor(temp, mockPolicySetType); + + when(mockPolicySetType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null); + + processor.policySet(mockPolicySetType, ""); + verify(mockPolicySetType, atLeast(1)).getTarget(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + } + + @Test + public void testHtmlProcessorPolicySetNotEmpty() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + anyOfList.add(new AnyOfType()); + + when(mockPolicySetType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null); + + processor = new HtmlProcessor(temp, mockPolicySetType); + processor.policySet(mockPolicySetType, ""); + verify(mockPolicySetType, atLeast(1)).getTarget(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference(); + } + + @Test + public void testHtmlProcessorRule() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + RuleType mockRuleType = Mockito.mock(RuleType.class); + ConditionType mockConditionType = Mockito.mock(ConditionType.class); + ObligationExpressionsType mockOESType = Mockito.mock(ObligationExpressionsType.class); + ObligationExpressionType mockOEType = Mockito.mock(ObligationExpressionType.class); + EffectType effectTypePermit = EffectType.PERMIT; + processor = new HtmlProcessor(temp, mockPolicySetType); + + List<ObligationExpressionType> oblList = new ArrayList<ObligationExpressionType>(); + oblList.add(mockOEType); + + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockRuleType.getRuleId()).thenReturn(null); + when(mockRuleType.getTarget()).thenReturn(null); + when(mockRuleType.getCondition()).thenReturn(mockConditionType); + when(mockRuleType.getObligationExpressions()).thenReturn(mockOESType); + when(mockOESType.getObligationExpression()).thenReturn(oblList); + when(mockOEType.getFulfillOn()).thenReturn(effectTypePermit); + + processor.rule(mockRuleType); + + verify(mockRuleType, atLeast(1)).getRuleId(); + verify(mockRuleType, atLeast(1)).getTarget(); + verify(mockRuleType, atLeast(1)).getCondition(); + verify(mockRuleType, atLeast(1)).getObligationExpressions(); + verify(mockOESType, atLeast(1)).getObligationExpression(); + verify(mockOEType, atLeast(1)).getFulfillOn(); + + JAXBElement<?> mockJaxBElement = Mockito.mock(JAXBElement.class); + Object mockValueObject = Mockito.mock(Object.class); + + doReturn(mockJaxBElement).when(mockConditionType).getExpression(); + doReturn(mockValueObject).when(mockJaxBElement).getValue(); + + try { + processor.rule(mockRuleType); + fail(); + } catch (IllegalArgumentException e) { + verify(mockConditionType, atLeast(1)).getExpression(); + verify(mockJaxBElement, atLeast(1)).getValue(); + } + } + + @Test + public void testHtmlProcessorRuleNullEmptyList() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + RuleType mockRuleType = Mockito.mock(RuleType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + EffectType effectTypePermit = EffectType.PERMIT; + AdviceExpressionsType mockAdviceExsType = Mockito.mock(AdviceExpressionsType.class); + AdviceExpressionType mockAdviceEx = Mockito.mock(AdviceExpressionType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + List<AdviceExpressionType> adviceExList = new ArrayList<AdviceExpressionType>(); + adviceExList.add(mockAdviceEx); + + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockRuleType.getRuleId()).thenReturn(null); + when(mockRuleType.getTarget()).thenReturn(mockTargetType); + when(mockRuleType.getObligationExpressions()).thenReturn(null); + when(mockRuleType.getAdviceExpressions()).thenReturn(mockAdviceExsType); + when(mockTargetType.getAnyOf()).thenReturn(null); + when(mockAdviceExsType.getAdviceExpression()).thenReturn(adviceExList); + when(mockAdviceEx.getAttributeAssignmentExpression()).thenReturn(null); + when(mockAdviceEx.getAppliesTo()).thenReturn(effectTypePermit); + + processor.rule(mockRuleType); + + verify(mockRuleType, atLeast(1)).getEffect(); + verify(mockRuleType, atLeast(1)).getRuleId(); + verify(mockRuleType, atLeast(1)).getTarget(); + verify(mockRuleType, atLeast(1)).getCondition(); + verify(mockRuleType, atLeast(1)).getObligationExpressions(); + verify(mockRuleType, atLeast(1)).getAdviceExpressions(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + verify(mockAdviceExsType, atLeast(1)).getAdviceExpression(); + verify(mockAdviceEx, atLeast(1)).getAttributeAssignmentExpression(); + verify(mockAdviceEx, atLeast(1)).getAppliesTo(); + + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + processor.rule(mockRuleType); + verify(mockTargetType, atLeast(1)).getAnyOf(); + } + + @Test + public void testHtmlProcessorRuleNonNullObjects() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + RuleType mockRuleType = Mockito.mock(RuleType.class); + TargetType mockTargetType = Mockito.mock(TargetType.class); + AdviceExpressionsType mockAdvice = Mockito.mock(AdviceExpressionsType.class); + ObligationExpressionsType mockObEx = Mockito.mock(ObligationExpressionsType.class); + AdviceExpressionType adviceExpTypeMock = Mockito.mock(AdviceExpressionType.class); + ObligationExpressionType mockObExType = Mockito.mock(ObligationExpressionType.class); + EffectType effectTypePermit = EffectType.PERMIT; + processor = new HtmlProcessor(temp, mockPolicySetType); + + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + anyOfList.add(new AnyOfType()); + + List<AdviceExpressionType> adviceList = new ArrayList<AdviceExpressionType>(); + adviceList.add(adviceExpTypeMock); + + List<AttributeAssignmentExpressionType> attrList = new ArrayList<AttributeAssignmentExpressionType>(); + + List<ObligationExpressionType> obExList = new ArrayList<ObligationExpressionType>(); + obExList.add(mockObExType); + + List<Object> contentList = new ArrayList<>(); + contentList.add(new Object()); + + when(mockRuleType.getRuleId()).thenReturn(""); + when(mockRuleType.getTarget()).thenReturn(mockTargetType); + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + when(mockRuleType.getAdviceExpressions()).thenReturn(mockAdvice); + when(mockAdvice.getAdviceExpression()).thenReturn(adviceList); + when(mockRuleType.getObligationExpressions()).thenReturn(mockObEx); + when(mockObEx.getObligationExpression()).thenReturn(obExList); + when(mockObExType.getAttributeAssignmentExpression()).thenReturn(null); + when(mockObExType.getFulfillOn()).thenReturn(effectTypePermit); + when(adviceExpTypeMock.getAdviceId()).thenReturn(""); + when(adviceExpTypeMock.getAppliesTo()).thenReturn(effectTypePermit); + when(adviceExpTypeMock.getAttributeAssignmentExpression()).thenReturn(attrList); + + processor.rule(mockRuleType); + + verify(mockRuleType, atLeast(1)).getRuleId(); + verify(mockRuleType, atLeast(1)).getTarget(); + verify(mockRuleType, atLeast(1)).getEffect(); + verify(mockRuleType, atLeast(1)).getAdviceExpressions(); + verify(mockRuleType, atLeast(1)).getObligationExpressions(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + verify(mockObEx, atLeast(1)).getObligationExpression(); + verify(mockObExType, atLeast(1)).getAttributeAssignmentExpression(); + verify(mockObExType, atLeast(1)).getFulfillOn(); + verify(mockAdvice, atLeast(1)).getAdviceExpression(); + verify(adviceExpTypeMock, atLeast(1)).getAdviceId(); + verify(adviceExpTypeMock, atLeast(1)).getAppliesTo(); + verify(adviceExpTypeMock, atLeast(1)).getAttributeAssignmentExpression(); + } + + @Test + public void testHtmlProcessorOnPreVisitRule() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = null; + RuleType mockRuleType = Mockito.mock(RuleType.class); + EffectType effectTypePermit = EffectType.PERMIT; + TargetType mockTargetType = Mockito.mock(TargetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + anyOfList.add(new AnyOfType()); + + when(mockRuleType.getCondition()).thenReturn(null); + when(mockRuleType.getDescription()).thenReturn(null); + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockRuleType.getTarget()).thenReturn(mockTargetType); + when(mockTargetType.getAnyOf()).thenReturn(anyOfList); + + CallbackResult callbackResult = processor.onPreVisitRule(mockPolicyType, mockRuleType); + assertNotNull(callbackResult); + + verify(mockRuleType, atLeast(1)).getCondition(); + verify(mockRuleType, atLeast(1)).getDescription(); + verify(mockRuleType, atLeast(1)).getEffect(); + verify(mockRuleType, atLeast(1)).getTarget(); + verify(mockRuleType, atLeast(1)).getAdviceExpressions(); + verify(mockTargetType, atLeast(1)).getAnyOf(); + + mockPolicyType = Mockito.mock(PolicyType.class); + when(mockRuleType.getDescription()).thenReturn(""); + + callbackResult = processor.onPreVisitRule(mockPolicyType, mockRuleType); + assertNotNull(callbackResult); + } + + @Test + public void testHtmlProcessorOnPostVisitRule() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + PolicyType mockPolicyType = null; + RuleType mockRuleType = Mockito.mock(RuleType.class); + + processor = new HtmlProcessor(temp, mockPolicySetType); + CallbackResult callbackResult = processor.onPostVisitRule(mockPolicyType, mockRuleType); + assertNotNull(callbackResult); + + mockPolicyType = Mockito.mock(PolicyType.class); + callbackResult = processor.onPostVisitRule(mockPolicyType, mockRuleType); + assertNotNull(callbackResult); + } + + @Test + public void testHtmlProcessorProcessAttributeAssignments() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + RuleType mockRuleType = Mockito.mock(RuleType.class); + EffectType effectTypePermit = EffectType.PERMIT; + ObligationExpressionsType mockOblExsType = Mockito.mock(ObligationExpressionsType.class); + + ObligationExpressionType mockOblExTypeListObj = Mockito.mock(ObligationExpressionType.class); + List<ObligationExpressionType> oblExTypeList = new ArrayList<ObligationExpressionType>(); + oblExTypeList.add(mockOblExTypeListObj); + + AttributeAssignmentExpressionType mockattrAssignListObj = Mockito.mock(AttributeAssignmentExpressionType.class); + List<AttributeAssignmentExpressionType> attrAssignList = new ArrayList<AttributeAssignmentExpressionType>(); + attrAssignList.add(mockattrAssignListObj); + + JAXBElement<?> jaxbElementMock = Mockito.mock(JAXBElement.class); + AttributeValueType attrValTypeMock = Mockito.mock(AttributeValueType.class); + AttributeDesignatorType attrDesignTypeMock = Mockito.mock(AttributeDesignatorType.class); + AttributeSelectorType attrSelTypeMock = Mockito.mock(AttributeSelectorType.class); + ApplyType applyTypeMock = Mockito.mock(ApplyType.class); + Object genericObjectMock = Mockito.mock(Object.class); + + Object mockContentListObject = Mockito.mock(Object.class); + List<Object> contentList = new ArrayList<Object>(); + contentList.add(mockContentListObject); + contentList.add(mockContentListObject); + + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockRuleType.getObligationExpressions()).thenReturn(mockOblExsType); + when(mockOblExsType.getObligationExpression()).thenReturn(oblExTypeList); + when(mockOblExTypeListObj.getAttributeAssignmentExpression()).thenReturn(attrAssignList); + when(mockOblExTypeListObj.getFulfillOn()).thenReturn(effectTypePermit); + when(mockattrAssignListObj.getCategory()).thenReturn(""); + when(mockattrAssignListObj.getAttributeId()).thenReturn(""); + doReturn(jaxbElementMock).when(mockattrAssignListObj).getExpression(); + doReturn(attrValTypeMock).when(jaxbElementMock).getValue(); + when(attrValTypeMock.getContent()).thenReturn(contentList); + + processor.rule(mockRuleType); + + verify(mockRuleType, atLeast(1)).getEffect(); + verify(mockRuleType, atLeast(1)).getObligationExpressions(); + verify(mockOblExsType, atLeast(1)).getObligationExpression(); + verify(mockOblExTypeListObj, atLeast(1)).getAttributeAssignmentExpression(); + verify(mockOblExTypeListObj, atLeast(1)).getFulfillOn(); + verify(mockattrAssignListObj, atLeast(1)).getExpression(); + verify(jaxbElementMock, atLeast(1)).getValue(); + verify(attrValTypeMock, atLeast(1)).getContent(); + + doReturn(attrDesignTypeMock).when(jaxbElementMock).getValue(); + processor.rule(mockRuleType); + verify(jaxbElementMock, atLeast(1)).getValue(); + + doReturn(attrSelTypeMock).when(jaxbElementMock).getValue(); + processor.rule(mockRuleType); + verify(jaxbElementMock, atLeast(1)).getValue(); + + doReturn(applyTypeMock).when(jaxbElementMock).getValue(); + processor.rule(mockRuleType); + verify(jaxbElementMock, atLeast(1)).getValue(); + + doReturn(genericObjectMock).when(jaxbElementMock).getValue(); + processor.rule(mockRuleType); + verify(jaxbElementMock, atLeast(1)).getValue(); + } + + @Test + public void testHtmlProcessorTarget() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + processor.target(null); + + AnyOfType mockAnyOfType = Mockito.mock(AnyOfType.class); + List<AnyOfType> anyOfList = new ArrayList<AnyOfType>(); + anyOfList.add(mockAnyOfType); + anyOfList.add(mockAnyOfType); // adding duplicate element + + AllOfType mockAllOfType = Mockito.mock(AllOfType.class); + List<AllOfType> allOfTypeList = new ArrayList<AllOfType>(); + allOfTypeList.add(mockAllOfType); + allOfTypeList.add(mockAllOfType); // adding duplicate element + + MatchType mockMatchType = Mockito.mock(MatchType.class); + List<MatchType> matchTypeList = new ArrayList<MatchType>(); + matchTypeList.add(mockMatchType); + matchTypeList.add(mockMatchType); // adding duplicate element + + AttributeValueType mockAttrValType = Mockito.mock(AttributeValueType.class); + AttributeDesignatorType mockAttrDesType = Mockito.mock(AttributeDesignatorType.class); + AttributeSelectorType mockAttrSelType = Mockito.mock(AttributeSelectorType.class); + + List<Object> contentList = new ArrayList<Object>(); + + when(mockAnyOfType.getAllOf()).thenReturn(allOfTypeList); + when(mockAllOfType.getMatch()).thenReturn(matchTypeList); + when(mockMatchType.getAttributeValue()).thenReturn(mockAttrValType); + when(mockMatchType.getMatchId()).thenReturn(XACML1.ID_FUNCTION_STRING_EQUAL.stringValue()); + when(mockMatchType.getAttributeDesignator()).thenReturn(mockAttrDesType); + when(mockAttrValType.getDataType()).thenReturn(""); + when(mockAttrValType.getContent()).thenReturn(contentList); + when(mockAttrDesType.getCategory()).thenReturn(""); + when(mockAttrDesType.getAttributeId()).thenReturn(""); + when(mockAttrDesType.getIssuer()).thenReturn(""); + when(mockAttrDesType.getDataType()).thenReturn(""); + processor.target(anyOfList); + verify(mockAnyOfType, atLeast(1)).getAllOf(); + verify(mockAllOfType, atLeast(1)).getMatch(); + verify(mockMatchType, atLeast(1)).getAttributeValue(); + verify(mockMatchType, atLeast(1)).getMatchId(); + verify(mockMatchType, atLeast(1)).getAttributeDesignator(); + verify(mockAttrValType, atLeast(1)).getDataType(); + verify(mockAttrValType, atLeast(1)).getContent(); + verify(mockAttrDesType, atLeast(1)).getCategory(); + verify(mockAttrDesType, atLeast(1)).getAttributeId(); + verify(mockAttrDesType, atLeast(1)).getIssuer(); + verify(mockAttrDesType, atLeast(1)).getDataType(); + + when(mockMatchType.getAttributeDesignator()).thenReturn(null); + when(mockMatchType.getAttributeSelector()).thenReturn(mockAttrSelType); + when(mockAttrSelType.getCategory()).thenReturn(""); + when(mockAttrSelType.getContextSelectorId()).thenReturn(""); + when(mockAttrSelType.getDataType()).thenReturn(""); + processor.target(anyOfList); + verify(mockMatchType, atLeast(1)).getAttributeDesignator(); + verify(mockMatchType, atLeast(1)).getAttributeSelector(); + verify(mockAttrSelType, atLeast(1)).getCategory(); + verify(mockAttrSelType, atLeast(1)).getContextSelectorId(); + verify(mockAttrSelType, atLeast(1)).getDataType(); + + when(mockMatchType.getAttributeDesignator()).thenReturn(null); + when(mockMatchType.getAttributeSelector()).thenReturn(null); + processor.target(anyOfList); + verify(mockMatchType, atLeast(1)).getAttributeDesignator(); + verify(mockMatchType, atLeast(1)).getAttributeSelector(); + } + + @Test + public void testHtmlProcessorStringifyExpression() { + PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class); + processor = new HtmlProcessor(temp, mockPolicySetType); + + RuleType mockRuleType = Mockito.mock(RuleType.class); + ConditionType mockConditionType = Mockito.mock(ConditionType.class); + JAXBElement<?> mockJAXBElement = Mockito.mock(JAXBElement.class); + EffectType effectTypePermit = EffectType.PERMIT; + Object mockExpressObject = Mockito.mock(Object.class); + AttributeDesignatorType mockAttrDesType = Mockito.mock(AttributeDesignatorType.class); + AttributeSelectorType mockAttrSelType = Mockito.mock(AttributeSelectorType.class); + AttributeValueType mockAttrValType = Mockito.mock(AttributeValueType.class); + VariableReferenceType mockVarRefType = Mockito.mock(VariableReferenceType.class); + + Object mockContentObject = Mockito.mock(Object.class); + List<Object> contentList = new ArrayList<Object>(); + contentList.add(mockContentObject); + + when(mockRuleType.getEffect()).thenReturn(effectTypePermit); + when(mockRuleType.getCondition()).thenReturn(mockConditionType); + doReturn(mockJAXBElement).when(mockConditionType).getExpression(); + doReturn(mockExpressObject).when(mockJAXBElement).getValue(); + + try { + processor.rule(mockRuleType); + fail(); + } catch (IllegalArgumentException e) { + verify(mockRuleType, atLeast(1)).getEffect(); + verify(mockRuleType, atLeast(1)).getCondition(); + verify(mockConditionType, atLeast(1)).getExpression(); + verify(mockJAXBElement, atLeast(1)).getValue(); + } + + doReturn(mockAttrDesType).when(mockJAXBElement).getValue(); + when(mockAttrDesType.getCategory()).thenReturn(""); + when(mockAttrDesType.getAttributeId()).thenReturn(""); + when(mockAttrDesType.getDataType()).thenReturn(""); + processor.rule(mockRuleType); + verify(mockJAXBElement, atLeast(1)).getValue(); + verify(mockAttrDesType, atLeast(1)).getCategory(); + verify(mockAttrDesType, atLeast(1)).getAttributeId(); + verify(mockAttrDesType, atLeast(1)).getDataType(); + + doReturn(mockAttrSelType).when(mockJAXBElement).getValue(); + when(mockAttrSelType.getPath()).thenReturn("SamplePath/text()"); + processor.rule(mockRuleType); + verify(mockJAXBElement, atLeast(1)).getValue(); + verify(mockAttrSelType, atLeast(1)).getPath(); + + when(mockAttrSelType.getPath()).thenReturn(""); + processor.rule(mockRuleType); + verify(mockJAXBElement, atLeast(1)).getValue(); + verify(mockAttrSelType, atLeast(1)).getPath(); + + doReturn(mockAttrValType).when(mockJAXBElement).getValue(); + when(mockAttrValType.getContent()).thenReturn(contentList); + processor.rule(mockRuleType); + verify(mockJAXBElement, atLeast(1)).getValue(); + verify(mockAttrValType, atLeast(1)).getContent(); + + doReturn(mockVarRefType).when(mockJAXBElement).getValue(); + processor.rule(mockRuleType); + verify(mockJAXBElement, atLeast(1)).getValue(); + } +} 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 dab2cba53..2f079f139 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -23,6 +23,7 @@ package org.onap.policy.conf; import static org.junit.Assert.assertNull; + import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; @@ -30,6 +31,10 @@ import org.mockito.Mockito; import org.onap.policy.controller.PolicyController; public class HibernateSessionTest { + + /** + * setup. + */ @Before public void setup() { PolicyController.setLogdbUrl("testURL"); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java new file mode 100644 index 000000000..e34cab45e --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controller; + +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.att.research.xacml.api.XACML3; +import java.io.IOException; +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.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import org.junit.Test; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +public class ActionPolicyControllerTest { + + @Test + public void testBasicConstructor() throws IOException { + ActionPolicyController controller = new ActionPolicyController(); + final PolicyRestAdapter adapter = new PolicyRestAdapter(); + // + // Cover the simple if instance branch + // + assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException(); + } + + @Test + public void testNoDescriptionNoTargetType() throws IOException { + // + // Do the test - with no description and + // no TargetType to cover those branches. + // + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setPolicyData(new PolicyType()); + adapter.setPolicyName("name"); + ActionPolicyController controller = new ActionPolicyController(); + assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException(); + } + + @Test + public void testWithDescriptionEmptyTargetType() throws IOException { + // + // Create a simple PolicyType + // + PolicyType policy = new PolicyType(); + policy.setTarget(new TargetType()); + policy.setDescription("i am a description. @CreatedBy: policy designer"); + // + // Now do the test - description and + // TargetType but its empty + // + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setPolicyData(policy); + adapter.setPolicyName("name"); + ActionPolicyController controller = new ActionPolicyController(); + assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException(); + } + + + @Test + public void testWithTargetTypeWithAnyOf() throws IOException { + // + // Create TargetType with empty AnyOf + // + AttributeValueType value = new AttributeValueType(); + value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + value.getContent().add(new String("value")); + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId("foo:bar"); + designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue()); + + MatchType match = new MatchType(); + match.setMatchId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue()); + match.setAttributeValue(value); + match.setAttributeDesignator(designator); + AllOfType allOf = new AllOfType(); + allOf.getMatch().add(match); + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOf); + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + // + // Create a simple Rule with NO obligations but a Condition + // + RuleType rule = new RuleType(); + rule.setRuleId("id:rule"); + rule.setEffect(EffectType.PERMIT); + + AttributeValueType expressionValue = new AttributeValueType(); + expressionValue.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + expressionValue.getContent().add(new String("a string value")); + + designator = new AttributeDesignatorType(); + designator.setAttributeId("foo:bar"); + designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue()); + + ApplyType applyOneAndOnly = new ApplyType(); + applyOneAndOnly.setDescription("apply this"); + applyOneAndOnly.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue()); + applyOneAndOnly.getExpression().add(new ObjectFactory().createAttributeDesignator(designator)); + + ApplyType applyOneAndOnly2 = new ApplyType(); + applyOneAndOnly2.setDescription("apply this"); + applyOneAndOnly2.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue()); + applyOneAndOnly2.getExpression().add(new ObjectFactory().createAttributeValue(expressionValue)); + + ApplyType apply = new ApplyType(); + apply.setDescription("apply this"); + apply.setFunctionId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue()); + apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly)); + apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly2)); + + + ConditionType condition = new ConditionType(); + condition.setExpression(new ObjectFactory().createApply(apply)); + rule.setCondition(condition); + // + // Create a simple Rule WITH obligations + // + AttributeValueType val = new AttributeValueType(); + val.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + val.getContent().add(new String("obligation data")); + + AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType(); + assignment.setAttributeId("ob:id:1"); + assignment.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue()); + assignment.setExpression(new ObjectFactory().createAttributeValue(val)); + + AttributeValueType val2 = new AttributeValueType(); + val2.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + val2.getContent().add(new String("iamperformer")); + + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("performer"); + assignment2.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue()); + assignment2.setExpression(new ObjectFactory().createAttributeValue(val2)); + + ObligationExpressionType ob = new ObligationExpressionType(); + ob.setFulfillOn(EffectType.PERMIT); + ob.setObligationId("id:obligation"); + ob.getAttributeAssignmentExpression().add(assignment); + ob.getAttributeAssignmentExpression().add(assignment2); + ObligationExpressionsType obs = new ObligationExpressionsType(); + obs.getObligationExpression().add(ob); + RuleType obligationRule = new RuleType(); + obligationRule.setRuleId("id:rule:obligations"); + obligationRule.setEffect(EffectType.DENY); + obligationRule.setObligationExpressions(obs); + // + // Create a PolicyType + // + PolicyType policy = new PolicyType(); + policy.setDescription("i am a description. @CreatedBy: policy designer"); + policy.setTarget(target); + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(obligationRule); + // + // Add something the ActionPolicyController will skip over + // to catch that branch + // + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(new VariableDefinitionType()); + // + // Now do the test - description and + // TargetType but its empty + // + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setPolicyData(policy); + adapter.setPolicyName("name"); + ActionPolicyController controller = new ActionPolicyController(); + assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException(); + } +} 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 a4999ff42..eccab040c 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,18 +19,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; + import java.io.BufferedReader; +import java.io.IOException; 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.HttpServletResponse; import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Test; @@ -49,25 +56,26 @@ public class AdminTabControllerTest { private static CommonClassDao commonClassDao; private HttpServletRequest request; private MockHttpServletResponse response; + private AdminTabController admin; + /** + * Before. + * + * @throws Exception Exception + */ @Before public void setUp() throws Exception { - + admin = new AdminTabController(); 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(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"); @@ -78,11 +86,10 @@ public class AdminTabControllerTest { @Test public void testGetAdminRole() { - AdminTabController admin = new AdminTabController(); + assertNotNull(AdminTabController.getCommonClassDao()); try { admin.getAdminTabEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("lockdowndata")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -91,7 +98,6 @@ public class AdminTabControllerTest { @Test public void testSaveAdminRole() throws Exception { - AdminTabController admin = new AdminTabController(); String data = "{\"lockdowndata\":{\"lockdown\":true}}"; BufferedReader reader = new BufferedReader(new StringReader(data)); try { @@ -104,4 +110,18 @@ public class AdminTabControllerTest { fail(); } } + + @SuppressWarnings("unchecked") + @Test + public void testGetAdminTabEntityDataException() throws IOException { + HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + when(mockResponse.getWriter()).thenThrow(IOException.class); + admin.getAdminTabEntityData(request, mockResponse); + verify(mockResponse).getWriter(); + } + + @Test + public void testSaveAdminTabLockdownValueException() throws IOException { + assertNull(admin.saveAdminTabLockdownValue(request, response)); + } } 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 5dd5d7ee3..95d566278 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,36 +19,71 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.pap.PAPException; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mockito; +import org.onap.policy.model.Roles; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.web.support.AppUtils; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) public class AutoPushControllerTest { - private PolicyController controller = new PolicyController();; + private PolicyController controller = new PolicyController(); private AutoPushController apController = new AutoPushController(); + private static HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); + private static HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); + private static PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + private static HttpSession mockSession = Mockito.mock(HttpSession.class); + private static User mockUser = Mockito.mock(User.class); + private static List<Object> rolesList = new ArrayList<>(); + @Rule public ExpectedException thrown = ExpectedException.none(); + @BeforeClass + public static void setupMocks() { + when(mockRequest.getSession(false)).thenReturn(mockSession); + when(AppUtils.getSession(mockRequest)).thenReturn(mockSession); + when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser); + when(mockUser.getOrgUserId()).thenReturn(""); + when(mockPolicyController.getRoles(any(String.class))).thenReturn(rolesList); + } + @Test public void testAutoPushSetGet() throws IOException { - // Get and set tests apController.setPolicyController(controller); assertEquals(apController.getPolicyController(), controller); } @@ -75,7 +110,7 @@ public class AutoPushControllerTest { } @Test(expected = NullPointerException.class) - public void testRefresh() throws IOException { + public void testRefreshGroupsNull() throws IOException { apController.refreshGroups(); } @@ -88,22 +123,105 @@ public class AutoPushControllerTest { 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); + PolicyController policyController = Mockito.mock(PolicyController.class); + PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(policyController); + Mockito.when(policyController.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); + assertEquals(HttpServletResponse.SC_OK, response.getStatusCode()); // Test push apController.pushPolicyToPDPGroup(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + assertEquals(HttpServletResponse.SC_OK, response.getStatusCode()); // Test remove apController.removePDPGroup(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + assertEquals(HttpServletResponse.SC_OK, response.getStatusCode()); + } + + @Test + public void testRefreshGroupsSuccess() throws PAPException { + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class); + Set<OnapPDPGroup> onapPDPGroups = new HashSet<>(); + when(mockPolicyController.getPapEngine()).thenReturn(mockPAPPolicyEngine); + when(mockPAPPolicyEngine.getOnapPDPGroups()).thenReturn(onapPDPGroups); + apController.setPolicyController(mockPolicyController); + apController.refreshGroups(); + verify(mockPolicyController).getPapEngine(); + verify(mockPAPPolicyEngine).getOnapPDPGroups(); + } + + @SuppressWarnings("unchecked") + @Test + public void testRefreshGroups() throws PAPException { + PolicyController mockPolicyController = Mockito.mock(PolicyController.class); + PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class); + when(mockPolicyController.getPapEngine()).thenReturn(mockPAPPolicyEngine); + when(mockPAPPolicyEngine.getOnapPDPGroups()).thenThrow(PAPException.class); + apController.setPolicyController(mockPolicyController); + apController.refreshGroups(); + verify(mockPolicyController).getPapEngine(); + verify(mockPAPPolicyEngine).getOnapPDPGroups(); + } + + @Test + public void testGetPolicyGroupContainerData() throws Exception { + Roles superAdmin = new Roles(); + Roles superEditor = new Roles(); + Roles superGuest = new Roles(); + rolesList.add(superAdmin); + rolesList.add(superEditor); + rolesList.add(superGuest); + + apController.setPolicyController(mockPolicyController); + apController.getPolicyGroupContainerData(mockRequest, mockResponse); + + verify(mockRequest, atLeast(1)).getSession(false); + verify(mockUser, atLeast(1)).getOrgUserId(); + verify(mockPolicyController, atLeast(1)).getRoles(any(String.class)); + } + + @Test + public void testGetPolicyGroupContainerDataWithScope() throws Exception { + Roles superAdmin = new Roles(); + superAdmin.setScope("super-admin-scope"); + Roles superEditor = new Roles(); + superEditor.setScope("super-editor-scope"); + Roles superGuest = new Roles(); + superGuest.setScope("super-guest-scope"); + rolesList.add(superAdmin); + rolesList.add(superEditor); + rolesList.add(superGuest); + + apController.setPolicyController(mockPolicyController); + apController.getPolicyGroupContainerData(mockRequest, mockResponse); + + verify(mockRequest, atLeast(1)).getSession(false); + verify(mockUser, atLeast(1)).getOrgUserId(); + verify(mockPolicyController, atLeast(1)).getRoles(any(String.class)); + } + + @Test + public void testGetPolicyGroupContainerDataWithRole() throws Exception { + Roles superAdmin = new Roles(); + superAdmin.setRole("super-admin"); + Roles superEditor = new Roles(); + superEditor.setRole("super-editor"); + Roles superGuest = new Roles(); + superGuest.setRole("super-guest"); + rolesList.add(superAdmin); + rolesList.add(superEditor); + rolesList.add(superGuest); + + apController.setPolicyController(mockPolicyController); + apController.getPolicyGroupContainerData(mockRequest, mockResponse); + + verify(mockRequest, atLeast(1)).getSession(false); + verify(mockUser, atLeast(1)).getOrgUserId(); + verify(mockPolicyController, atLeast(1)).getRoles(any(String.class)); } } 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 e4ededa1f..8966f47a9 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 @@ -22,7 +22,6 @@ package org.onap.policy.controller; - import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; @@ -70,10 +69,9 @@ import org.springframework.mock.web.MockHttpServletResponse; /** * 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. + * <p/>All JUnits are designed to run in the local development environment where they have write privileges + * and can execute time-sensitive tasks. * */ @@ -85,11 +83,15 @@ public class CreateDcaeMicroServiceControllerTest { private String configBodyString = null; private HttpServletRequest request = null; + /** + * setUp. + * + * @throws Exception should not throw one + */ @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.setModelName("modelName"); @@ -101,11 +103,11 @@ public class CreateDcaeMicroServiceControllerTest { + "CorrelationWindow=String:defaultValue-null:required-true:MANY-false:description-null," + "EmailNotification=String:defaultValue-null:required-true:MANY-false:description-null," + "CorrelationPriority=string:defaultValue-null:required-true:MANY-false:description-null,"); - testData.setRef_attributes("SymptomTriggerSignature=resource-model-symptomEntity:MANY-true:description-null," + testData.setRefAttributes("SymptomTriggerSignature=resource-model-symptomEntity:MANY-true:description-null," + "triggerSignature=resource-model-entity:MANY-true:description-null," + "SelectServerScope=SELECTSERVERSCOPE:MANY-false,logicalConnector=LOGICALCONNECTOR:MANY-false," + "ParentCorrelationTraversal=PARENTCORRELATIONTRAVERSAL:MANY-false,"); - testData.setSub_attributes( + testData.setSubAttributes( "{\"symptomAlarms\":{\"symptomContains\":\"SYMPTOMCONTAINS:defaultValue-null:required-true:MANY-false:" + "description-null\",\"symptomFilterValue\":\"string:defaultValue-null:" + "required-true:MANY-false:" @@ -136,6 +138,7 @@ public class CreateDcaeMicroServiceControllerTest { testData.setDataOrderInfo("triggerSignature.signaturesAlarm.alarmSignatures.alarmSignature[VnfType, Contains, " + "FilterValue]@SymptomTriggerSignature.signaturesSymptom.symptomSignatures." + "symptomSignature[symptomVnfType, symptomContains, symptomFilterValue]"); + List<Object> microServiceModelsData = new ArrayList<Object>(); microServiceModelsData.add(testData); // mock the getDataById() call @@ -159,15 +162,8 @@ public class CreateDcaeMicroServiceControllerTest { + "\"asdafadf\",\"guard\":\"True\",\"riskType\":\"sfsgs\",\"riskLevel\":\"1\"," + "\"priority\":\"1\",\"configName\":\"Search\",\"location\":\"Search\"," + "\"uuid\":\"Search\",\"policyScope\":\"PolicyScope_ssaaa123\"}}," - + "\"policyJSON\":{\"Correlation Priority\":\"testttt\",\"Correlation Window\":" - + "\"testttt\",\"Email Notification for failures\":\"sds@l.com\"," - + "\"Select Server Scope\":\"testttt\",\"Parent Correlation Name\":" - + "\"testttt\",\"Parent Correlation Traversal\":\"testttt\",\"logicalConnector\":" - + "\"OR\",\"triggerSignature@0.signaturesAlarm.alarmSignatures@0.traversal\":\"testttt\"," - + "\"triggerSignature@0.signaturesAlarm.alarmSignatures@0.alarmSignature@0.VnfType\":" - + "\" testttt\",\"triggerSignature@0.signaturesAlarm.alarmSignatures@0." - + "alarmSignature@0.Contains\":\"AND\",\"triggerSignature@0.signaturesAlarm." - + "alarmSignatures@0.alarmSignature@0.FilterValue\":\"testttt\"}}"; + + "\"policyJSON\":{\"DCAEProcessingRules@0.processingRules_json\":" + + "\"eyJuYW1lIjogIkpvaG4iLCAiYWdlIjogIjI4IiwgImNpdHkiOiAiTmV3IFlvcmsifQ==\"}}"; configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\"," + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\"," @@ -349,11 +345,8 @@ public class CreateDcaeMicroServiceControllerTest { try { root = JsonLoader.fromString(jsonString); restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - 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(); @@ -363,6 +356,7 @@ public class CreateDcaeMicroServiceControllerTest { AttributeDesignatorType designator = new AttributeDesignatorType(); designator.setAttributeId("guard"); matchType.setAttributeDesignator(designator); + AllOfType alltype = new AllOfType(); alltype.getMatch().add(matchType); // add a dummy MatchType object since while (matchList.size()>1 ...) @@ -377,8 +371,10 @@ public class CreateDcaeMicroServiceControllerTest { matchDummy.setAttributeDesignator(designatorDummy); alltype.getMatch().add(matchDummy); + AnyOfType anyOfType = new AnyOfType(); anyOfType.getAllOf().add(alltype); + TargetType target = new TargetType(); target.getAnyOf().add(anyOfType); // create RiskType attribute 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 6747e9669..8e1b8be87 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -22,7 +22,6 @@ package org.onap.policy.controller; - import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; @@ -31,6 +30,12 @@ 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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.fge.jackson.JsonLoader; + import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -39,9 +44,19 @@ 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 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; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -51,25 +66,12 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ConfigurationDataEntity; 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; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -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>}* * - * All JUnits are designed to run in the local development environment where they have write + * <p/>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 { @@ -94,26 +96,24 @@ public class CreateOptimizationControllerTest { 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\"}}"; + 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)); @@ -124,7 +124,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test + * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test. */ @Test @@ -141,15 +141,14 @@ public class CreateOptimizationControllerTest { PolicyRestAdapter policyData = null; try { root = JsonLoader.fromString(jsonString); - policyData = (PolicyRestAdapter) mapper.readValue( - root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + policyData = 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()); + assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); logger.debug("result.getJsonBody() : " + result.getJsonBody()); logger.debug("testSetDataToPolicyRestAdapter: exit"); @@ -157,7 +156,7 @@ public class CreateOptimizationControllerTest { /** * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse) - * method test + * method test. */ @Test @@ -181,8 +180,8 @@ public class CreateOptimizationControllerTest { 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); + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody")) + .thenReturn(optimizationModelsData); controller.getOptimizationTemplateData(request, response); @@ -200,7 +199,7 @@ public class CreateOptimizationControllerTest { /** * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse) - * method test + * method test. */ @Test @@ -225,8 +224,8 @@ public class CreateOptimizationControllerTest { optimizationModelsData.add(testData); // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", - "TestPolicyBody")).thenReturn(optimizationModelsData); + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody")) + .thenReturn(optimizationModelsData); controller.getModelServiceVersionData(request, response); assertTrue(response.getContentAsString() != null @@ -243,7 +242,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test + * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test. */ @Test @@ -266,8 +265,8 @@ public class CreateOptimizationControllerTest { try { root = JsonLoader.fromString(jsonString); - restAdapter = (PolicyRestAdapter) mapper.readValue( - root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(), + PolicyRestAdapter.class); PolicyType policyType = new PolicyType(); TargetType target = new TargetType(); @@ -386,7 +385,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test + * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test. */ @Test @@ -409,9 +408,7 @@ public class CreateOptimizationControllerTest { String fileName = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - fileName = - new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()) - .getAbsolutePath(); + fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath(); } catch (Exception e1) { logger.error("Exception Occured while loading file" + e1); } @@ -430,9 +427,7 @@ public class CreateOptimizationControllerTest { } /** - * - * @ Get File Stream - * + * @ Get File Stream. */ private class MockServletInputStream extends ServletInputStream { diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java new file mode 100644 index 000000000..79277d81d --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controller; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.XACML3; +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; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyEntity; + +public class CreatePolicyControllerTest { + + private PolicyEntity entity; + + /** + * before - sets up the mocked PolicyEntity. + */ + @Before + public void before() { + // + // PolicyEntity + // + ConfigurationDataEntity dataEntity = mock(ConfigurationDataEntity.class); + when(dataEntity.getConfigType()).thenReturn("configtype"); + entity = mock(PolicyEntity.class); + when(entity.getConfigurationData()).thenReturn(dataEntity); + } + + @Test + public void testEasyStuff() { + CreatePolicyController controller = new CreatePolicyController(); + PolicyRestAdapter adapter = new PolicyRestAdapter(); + controller.prePopulateBaseConfigPolicyData(adapter, null); + // + // Create a simple PolicyType + // + VariableDefinitionType var = new VariableDefinitionType(); + PolicyType policy = new PolicyType(); + policy.setDescription("i am a description. @CreatedBy: policy designer"); + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var); + adapter.setPolicyData(policy); + adapter.setPolicyName("name"); + controller.prePopulateBaseConfigPolicyData(adapter, entity); + } + + @Test + public void testBadDescription() { + PolicyRestAdapter adapter = new PolicyRestAdapter(); + // + // Create a simple PolicyType + // + VariableDefinitionType var = new VariableDefinitionType(); + PolicyType policy = new PolicyType(); + policy.setDescription("i am a description"); + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var); + adapter.setPolicyData(policy); + adapter.setPolicyName("name"); + CreatePolicyController controller = new CreatePolicyController(); + controller.prePopulateBaseConfigPolicyData(adapter, entity); + } + + @Test + public void testExpectedPolicyContents() { + AllOfType allOf = new AllOfType(); + allOf.getMatch().add(createMatchType("ONAPName", "ONAPName")); + allOf.getMatch().add(createMatchType("RiskType", "RiskType")); + allOf.getMatch().add(createMatchType("RiskLevel", "RiskLevel")); + allOf.getMatch().add(createMatchType("guard", "guard")); + allOf.getMatch().add(createMatchType("TTLDate", "TTLDate")); + allOf.getMatch().add(createMatchType("ConfigName", "ConfigName")); + allOf.getMatch().add(createMatchType("NA", "TTLDate")); + allOf.getMatch().add(createMatchType("custom", "custom")); + allOf.getMatch().add(createMatchType("custom", "custom")); + allOf.getMatch().add(createMatchType("custom", "custom")); + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + + RuleType rule = new RuleType(); + PolicyType policy = new PolicyType(); + policy.setDescription("i am a description. @CreatedBy: policy designer"); + policy.setTarget(target); + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setPolicyData(policy); + adapter.setPolicyName("name"); + CreatePolicyController controller = new CreatePolicyController(); + controller.prePopulateBaseConfigPolicyData(adapter, entity); + } + + private MatchType createMatchType(String strValue, String id) { + AttributeValueType value = new AttributeValueType(); + value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue()); + value.getContent().add(new String(strValue)); + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId(id); + + MatchType match = new MatchType(); + match.setAttributeValue(value); + match.setAttributeDesignator(designator); + + return match; + } + +} 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 f2ecea504..413849cd3 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * POLICY-SDK-APP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + 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; @@ -50,6 +54,11 @@ public class DashboardControllerTest { private Path repo; StdEngine engine = null; + /** + * setUp. + * + * @throws Exception should not get one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); @@ -84,8 +93,8 @@ public class DashboardControllerTest { public void testGetPAPStatusData() { try { controller.getPAPStatusData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("papTableDatas")); + assertTrue( + response.getContentAsString() != null && response.getContentAsString().contains("papTableDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -96,8 +105,8 @@ public class DashboardControllerTest { public void testGetPDPStatusData() { try { controller.getPDPStatusData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("pdpTableDatas")); + assertTrue( + response.getContentAsString() != null && response.getContentAsString().contains("pdpTableDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java index e9f953b87..1c744278a 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,9 @@ import static org.mockito.Mockito.mock; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; + import javax.servlet.http.HttpServletRequest; + import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.junit.Before; 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 1c1c0fbbd..372090fdf 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; +import static org.junit.Assert.assertEquals; 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; @@ -46,6 +51,11 @@ public class PDPControllerTest extends Mockito { private Set<StdPDPGroup> groups; private static List<Object> rolesdata; + /** + * Before. + * + * @throws Exception Exception + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); @@ -75,9 +85,9 @@ public class PDPControllerTest extends Mockito { } @Test - public void testPDPGroupData() { - HttpServletRequest request = mock(HttpServletRequest.class); - MockHttpServletResponse response = new MockHttpServletResponse(); + public void testPdpGroupData() { + final HttpServletRequest request = mock(HttpServletRequest.class); + final MockHttpServletResponse response = new MockHttpServletResponse(); PolicyController controller = mock(PolicyController.class); PDPController pdpController = new PDPController(); pdpController.setJunit(true);; @@ -86,10 +96,22 @@ public class PDPControllerTest extends Mockito { when(controller.getRoles("Test")).thenReturn(rolesdata); pdpController.getPDPGroupEntityData(request, response); try { - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("data")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("data")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); } } + + @Test + public void testPdpData() { + PdpData data = new PdpData(); + data.setId("id"); + assertEquals("id", data.getId()); + data.setDescription("foo"); + assertEquals("foo", data.getDescription()); + data.setJmxPort(0); + assertEquals(0, data.getJmxPort()); + data.setName("name"); + assertEquals("name", data.getName()); + } } 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 65077ae01..554c40f90 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; 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; @@ -43,17 +47,20 @@ public class PolicyControllerTest { private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class); private static CommonClassDao commonClassDao; + /** + * setUp. + * + * @throws Exception Should not throw one + */ @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")); + policyData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { e1.printStackTrace(); } @@ -61,6 +68,7 @@ public class PolicyControllerTest { entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyData); entity.setScope("com"); + List<Object> data = new ArrayList<>(); data.add(entity); when(commonClassDao.getDataByQuery( diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java index 1e4e62da1..37145655c 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * 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. @@ -17,20 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Collections; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -41,12 +43,12 @@ import org.onap.policy.rest.jpa.UserInfo; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) public class PolicyExportAndImportControllerTest { @Test public void testSetAndGet() { @@ -97,10 +99,9 @@ public class PolicyExportAndImportControllerTest { ClassLoader classLoader = getClass().getClassLoader(); // Test negative case - String file = - new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile()) - .getAbsolutePath(); - JSONObject json = controller.importRepositoryFile(file, request); + String file = new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile()) + .getAbsolutePath(); + String json = controller.importRepositoryFile(file, request); assertNull(json); // Another negative case 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 476eb6728..31b2dffb3 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; import java.util.Collections; + import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -35,15 +42,15 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.web.servlet.ModelAndView; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) +@PrepareForTest({UserUtils.class}) public class PolicyNotificationControllerTest { - @PrepareForTest({UserUtils.class}) @Test public void testWatch() throws IOException { // Mock user utilities @@ -60,16 +67,14 @@ public class PolicyNotificationControllerTest { PolicyNotificationController controller = new PolicyNotificationController(); controller.commonClassDao = dao; MockHttpServletRequest request = new MockHttpServletRequest(); - request.setBodyContent( - "{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n"); + 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"); + request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n"); response = new MockHttpServletResponse(); model = controller.watchPolicy(request, response); assertNull(model); 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 d665aae5e..e24525619 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * POLICY-SDK-APP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,17 +19,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; 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; @@ -47,6 +51,11 @@ public class PolicyRolesControllerTest { private PolicyRolesController controller = null; private static CommonClassDao commonClassDao; + /** + * Before. + * + * @throws Exception exception + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); @@ -59,8 +68,7 @@ public class PolicyRolesControllerTest { 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(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); logger.info("setUp: exit"); @@ -70,8 +78,7 @@ public class PolicyRolesControllerTest { public void testGetPolicyRolesEntityData() { try { controller.getPolicyRolesEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("rolesDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -82,8 +89,7 @@ public class PolicyRolesControllerTest { public void testGetPolicyScopesEntityData() { try { controller.getPolicyScopesEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("scopeDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("scopeDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -100,8 +106,7 @@ public class PolicyRolesControllerTest { when(request.getReader()).thenReturn(br); controller.SaveRolesEntityData(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("rolesDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); } catch (Exception e) { fail("Exception: " + e); } 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 2ad6d6a7e..56b2d1030 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,16 +19,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; + import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.springframework.web.servlet.ModelAndView; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; public class PolicyValidationControllerTest { @Test 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 e7212f109..2b1052044 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -24,8 +24,13 @@ package org.onap.policy.daoImp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + import java.io.File; import java.util.ArrayList; import java.util.Date; @@ -34,10 +39,15 @@ import java.util.Properties; import javax.script.SimpleBindings; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.h2.tools.Server; +import org.hibernate.Criteria; +import org.hibernate.HibernateException; +import org.hibernate.Session; import org.hibernate.SessionFactory; +import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.conf.HibernateSession; @@ -46,7 +56,7 @@ import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyRoles; import org.onap.policy.rest.jpa.PolicyVersion; -import org.onap.policy.rest.jpa.SystemLogDB; +import org.onap.policy.rest.jpa.SystemLogDb; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; @@ -61,6 +71,11 @@ public class CommonClassDaoImplTest { Server server; CommonClassDaoImpl commonClassDao; + /** + * setUp. + * + * @throws Exception Exception + */ @Before public void setUp() throws Exception { try { @@ -87,13 +102,13 @@ public class CommonClassDaoImplTest { CommonClassDaoImpl.setSessionfactory(sessionFactory); PolicyController.setLogTableLimit("1"); HibernateSession.setSession(sessionFactory); - SystemLogDB data1 = new SystemLogDB(); + SystemLogDb data1 = new SystemLogDb(); data1.setDate(new Date()); data1.setLogtype("INFO"); data1.setRemote("Test"); data1.setSystem("Test"); data1.setType("Test"); - SystemLogDB data2 = new SystemLogDB(); + SystemLogDb data2 = new SystemLogDb(); data2.setDate(new Date()); data2.setLogtype("error"); data2.setRemote("Test"); @@ -122,13 +137,13 @@ public class CommonClassDaoImplTest { userinfo.setUserName("Test"); commonClassDao.save(userinfo); OnapName onapName = new OnapName(); - onapName.setOnapName("Test"); + onapName.setName("Test"); onapName.setUserCreatedBy(userinfo); onapName.setUserModifiedBy(userinfo); onapName.setModifiedDate(new Date()); commonClassDao.save(onapName); - List<Object> list = commonClassDao.getData(OnapName.class); + List<?> list = commonClassDao.getData(OnapName.class); assertTrue(list.size() == 1); logger.debug(list.size()); logger.debug(list.get(0)); @@ -145,18 +160,17 @@ public class CommonClassDaoImplTest { try { // Add data UserInfo userinfo = new UserInfo(); - String loginId_userName = "Test"; - userinfo.setUserLoginId(loginId_userName); - userinfo.setUserName(loginId_userName); + String loginIdUserName = "Test"; + userinfo.setUserLoginId(loginIdUserName); + userinfo.setUserName(loginIdUserName); commonClassDao.save(userinfo); - List<Object> dataCur = - commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); + List<?> 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()); + assertEquals(loginIdUserName, cur.getUserLoginId()); + assertEquals(loginIdUserName, cur.getUserName()); assertFalse(dataCur.isEmpty()); @@ -183,13 +197,12 @@ public class CommonClassDaoImplTest { pe.setCreatedBy("Test"); commonClassDao.save(pe); - List<Object> dataCur = - commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); + List<?> 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))); + assertEquals(pe, (dataCur.get(0))); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -225,10 +238,10 @@ public class CommonClassDaoImplTest { 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); + List<?> dataCur = commonClassDao.getDataByQuery(query, params); assertTrue(1 == dataCur.size()); - assertEquals(pv, (PolicyVersion) dataCur.get(0)); + assertEquals(pv, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -243,11 +256,11 @@ public class CommonClassDaoImplTest { try { // Add data WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - String policyFileName = "banana"; watch.setLoginIds("Test"); watch.setPolicyName("bananaWatch"); commonClassDao.save(watch); + String policyFileName = "banana"; if (policyFileName.contains("/")) { policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); policyFileName = policyFileName.replace("/", File.separator); @@ -262,12 +275,12 @@ public class CommonClassDaoImplTest { String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; SimpleBindings params = new SimpleBindings(); params.put("policyFileName", policyFileName); - List<Object> dataCur = commonClassDao.getDataByQuery(query, params); + List<?> dataCur = commonClassDao.getDataByQuery(query, params); // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + assertEquals(watch, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -293,20 +306,19 @@ public class CommonClassDaoImplTest { commonClassDao.save(pe); String dbCheckName = "dummyScope:action"; - String[] splitDBCheckName = dbCheckName.split(":"); // Current Implementation - String query = - "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; + 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); + String[] splitDbCheckName = dbCheckName.split(":"); + params.put("splitDBCheckName1", splitDbCheckName[1] + "%"); + params.put("splitDBCheckName0", splitDbCheckName[0]); + List<?> dataCur = commonClassDao.getDataByQuery(query, params); // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof PolicyEntity); - assertEquals(pe, (PolicyEntity) dataCur.get(0)); + assertEquals(pe, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -328,17 +340,16 @@ public class CommonClassDaoImplTest { commonClassDao.save(watch); // Current Implementation - String query = - "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + 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); + List<?> dataCur = commonClassDao.getDataByQuery(query, params); // Assertions assertTrue(dataCur.size() == 1); assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable); - assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0)); + assertEquals(watch, dataCur.get(0)); } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -371,20 +382,19 @@ public class CommonClassDaoImplTest { String finalName = "banana' OR '1'='1"; // Current Implementation - String query = - "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + 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); + List<?> 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))); + assertFalse(watch.equals(dataCur.get(0))); + assertFalse(watch.equals(dataCur.get(0))); } } catch (Exception e) { logger.debug("Exception Occured" + e); @@ -399,19 +409,17 @@ public class CommonClassDaoImplTest { userInfo.setUserLoginId("TestID"); userInfo.setUserName("Test"); commonClassDao.save(userInfo); - List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", - "TestID:Test"); + List<?> 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"); + 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); + List<?> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class); assertTrue(data3.size() == 1); PolicyRoles roles = new PolicyRoles(); roles.setRole("admin"); @@ -422,8 +430,8 @@ public class CommonClassDaoImplTest { assertTrue(roles1.size() == 1); List<String> multipleData = new ArrayList<>(); multipleData.add("TestID:Test1"); - List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, - "userLoginId:userName", multipleData); + List<?> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", + multipleData); assertTrue(data4.size() == 1); commonClassDao.delete(data2); } catch (Exception e) { @@ -454,6 +462,70 @@ public class CommonClassDaoImplTest { } } + @SuppressWarnings("unchecked") + @Test + public void testExceptions() throws HibernateException { + SessionFactory sfMock = Mockito.mock(SessionFactory.class); + Session mockSession = Mockito.mock(Session.class); + Criteria crMock = Mockito.mock(Criteria.class); + Transaction mockTransaction = Mockito.mock(Transaction.class); + + CommonClassDaoImpl.setSessionfactory(sfMock); + + when(sfMock.openSession()).thenReturn(mockSession); + when(mockSession.createCriteria(OnapName.class)).thenReturn(crMock); + + when(crMock.list()).thenThrow(HibernateException.class); + when(mockSession.close()).thenThrow(HibernateException.class); + + when(mockSession.beginTransaction()).thenReturn(mockTransaction); + doThrow(HibernateException.class).when(mockTransaction).commit(); + + List<?> dataList = commonClassDao.getData(OnapName.class); + assertNull(dataList); + + List<?> dataByIdList = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test"); + assertNull(dataByIdList); + + commonClassDao.save(null); + commonClassDao.delete(null); + commonClassDao.update(null); + + List<?> dupEntryList = + commonClassDao.checkDuplicateEntry("TestID:Test", "userLoginId:userName", UserInfo.class); + assertNull(dupEntryList); + + List<PolicyRoles> userRoles = commonClassDao.getUserRoles(); + assertNull(userRoles); + + Object entityItem = commonClassDao.getEntityItem(UserInfo.class, "testColName", "testKey"); + assertNull(entityItem); + + commonClassDao.updateQuery("testQueryString"); + + List<String> dataByColumn = commonClassDao.getDataByColumn(UserInfo.class, "testColName"); + assertNull(dataByColumn); + + List<?> entityData = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "", null); + assertNull(entityData); + } + + @Test + public void testCheckExistingGroupListforUpdate() { + Object retObj = commonClassDao.checkExistingGroupListforUpdate("testString1", "testString2"); + assertNotNull(retObj); + assertTrue(retObj instanceof List); + List<?> retList = (List<?>) retObj; + assertTrue(retList.isEmpty()); + } + + @Test + public void testEmptyMethods() { + commonClassDao.deleteAll(); + commonClassDao.updateClAlarms("TestString1", "TestString2"); + commonClassDao.updateClYaml("TestString1", "TestString2"); + } + @After public void deleteDB() { sessionFactory.close(); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java new file mode 100644 index 000000000..44f034c20 --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.daoImp; + +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.conf.HibernateSession; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.SystemLogDb; + +public class SystemLogDbDaoImplTest { + private static Session mockSession = Mockito.mock(Session.class); + private static SessionFactory sfMock = Mockito.mock(SessionFactory.class); + private static Transaction mockTransaction = Mockito.mock(Transaction.class); + private SystemLogDbDaoImpl sysLogImpl = new SystemLogDbDaoImpl(); + + @SuppressWarnings("unchecked") + @BeforeClass + public static void setup() { + HibernateSession.setSession(sfMock); + + when(sfMock.openSession()).thenReturn(mockSession); + when(mockSession.beginTransaction()).thenReturn(mockTransaction); + + doThrow(HibernateException.class).when(mockTransaction).commit(); + when(mockSession.close()).thenThrow(HibernateException.class); + + PolicyController.setjUnit(true); + } + + @Test + public void testGettingLoggingData() { + List<SystemLogDb> loggingData = sysLogImpl.getLoggingData(); + assertNull(loggingData); + } + + @Test + public void testGetSystemAlertData() { + List<SystemLogDb> systemAlertData = sysLogImpl.getSystemAlertData(); + assertNull(systemAlertData); + } + + @AfterClass + public static void resetjUnit() { + PolicyController.setjUnit(false); + } +} 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 5117a05da..5204fc414 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 @@ -2,10 +2,8 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2019 Samsung - * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + ================================================================================ * 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 @@ -23,16 +21,27 @@ package org.onap.policy.model; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.pap.PAPException; +import java.awt.Checkbox; +import java.util.Set; import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; -import com.att.research.xacml.api.pap.PAPException; public class PDPGroupContainerTest { + private OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class); + private OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class); + private OnapPDP pdp = Mockito.mock(OnapPDP.class); private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class); private PDPGroupContainer container = new PDPGroupContainer(engine); @@ -44,13 +53,11 @@ public class PDPGroupContainerTest { 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); + container.updateGroup(group, "testUserName"); assertNull(container.getContainerPropertyIds()); assertEquals(container.getItemIds().size(), 0); assertEquals(container.getType(itemId), null); @@ -103,7 +110,7 @@ public class PDPGroupContainerTest { } @Test(expected = IndexOutOfBoundsException.class) - public void testGetIdByIndex() { + public void testGetIdByIndexException() { container.getIdByIndex(0); } @@ -113,7 +120,145 @@ public class PDPGroupContainerTest { } @Test(expected = IllegalArgumentException.class) - public void testGetItemIds() { + public void testGetItemIdsException() { container.getItemIds(0, 1); } + + @Test + public void testGetType() { + assertEquals(Boolean.class, container.getType("Default")); + assertEquals(Checkbox.class, container.getType("Selected")); + assertEquals(Set.class, container.getType("PDPs")); + assertEquals(Set.class, container.getType("Policies")); + assertEquals(Set.class, container.getType("PIP Configurations")); + assertEquals(String.class, container.getType("Id")); + assertEquals(String.class, container.getType("Name")); + assertEquals(String.class, container.getType("Description")); + assertEquals(String.class, container.getType("Status")); + } + + @Test + public void testContainerPAPExceptions() throws PAPException { + doThrow(PAPException.class).when(engine).getOnapPDPGroups(); + container.refreshGroups(); + + doThrow(PAPException.class).when(engine).setDefaultGroup(group); + container.makeDefault(group); + + doThrow(PAPException.class).when(engine).updatePDP(pdp); + container.updatePDP(pdp); + + doThrow(PAPException.class).when(engine).updateGroup(group); + container.updateGroup(group); + + doThrow(PAPException.class).when(engine).updateGroup(group, "testUserName"); + container.updateGroup(group, "testUserName"); + + doThrow(PAPException.class).when(engine).movePDP(pdp, group); + container.movePDP(pdp, group); + } + + @Test(expected = PAPException.class) + public void testContainerRemoveGroup() throws PAPException { + doThrow(PAPException.class).when(engine).removeGroup(group, newGroup); + container.removeGroup(group, newGroup); + } + + @Test(expected = PAPException.class) + public void testContainerRemovePDP() throws PAPException { + doThrow(PAPException.class).when(engine).removePDP(pdp); + container.removePDP(pdp, group); + } + + @Test(expected = UnsupportedOperationException.class) + public void testRemoveDefaultGroup() throws PAPException { + when(group.isDefaultGroup()).thenReturn(true); + container.removeGroup(group, newGroup); + } + + @Test + public void testGetItemIds() { + assertNotNull(container.getItemIds(0, 0)); + } + + @Test + public void testContainsId() { + assertFalse(container.containsId(group)); + } + + @Test + public void testGroupMethods() { + container.groups.add(group); + + Object retObj = container.getIdByIndex(0); + assertTrue(retObj instanceof OnapPDPGroup); + assertNotNull(retObj); + + Object retFirstItemId = container.firstItemId(); + assertTrue(retFirstItemId instanceof OnapPDPGroup); + assertNotNull(retFirstItemId); + + Object retLastItemId = container.lastItemId(); + assertTrue(retLastItemId instanceof OnapPDPGroup); + assertNotNull(retLastItemId); + + assertTrue(container.isFirstId(group)); + + assertTrue(container.isLastId(group)); + } + + @Test + public void testNextItemId() { + OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class); + Object retObj = null; + + container.groups.add(group); + container.groups.add(newGroup); + + assertNull(container.nextItemId(groupNotInList)); + assertNull(container.nextItemId(newGroup)); + + retObj = container.nextItemId(group); + assertNotNull(retObj); + assertTrue(retObj instanceof OnapPDPGroup); + } + + @Test + public void testPrevItemId() { + OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class); + Object retObj = null; + + container.groups.add(group); + container.groups.add(newGroup); + + assertNull(container.prevItemId(groupNotInList)); + assertNull(container.prevItemId(group)); + + retObj = container.prevItemId(newGroup); + assertNotNull(retObj); + assertTrue(retObj instanceof OnapPDPGroup); + } + + @Test + public void testRemoveNullItem() { + OnapPDPGroup nullGroup = null; + assertFalse(container.removeItem(nullGroup)); + } + + @Test(expected = UnsupportedOperationException.class) + public void testRemoveDefaultItem() { + when(group.getId()).thenReturn("Default"); + container.removeItem(group); + } + + @SuppressWarnings("unchecked") + @Test + public void testRemoveItem() throws PAPException { + assertTrue(container.removeItem(group)); + + PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class); + PDPGroupContainer groupContainer = new PDPGroupContainer(mockPAPPolicyEngine); + when(mockPAPPolicyEngine.getDefaultGroup()).thenThrow(PAPException.class); + assertFalse(groupContainer.removeItem(group)); + } } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java new file mode 100644 index 000000000..745579af9 --- /dev/null +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.model; + +import com.openpojo.reflection.filters.FilterPackageInfo; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +import org.junit.Test; + +public class RolesTest { + + @Test + public void testRolesSettersAndGetters() { + final Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build(); + validator.validate(RolesTest.class.getPackage().getName(), new FilterPackageInfo()); + } +} |