diff options
Diffstat (limited to 'ONAP-PAP-REST/src/test')
7 files changed, 685 insertions, 798 deletions
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java index 00553e0ee..6a3a9dc8d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,7 +24,7 @@ package org.onap.policy.pap.test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; - +import com.mockrunner.mock.web.MockServletInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -35,27 +35,23 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; -import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; -import org.onap.policy.common.ia.IntegrityAuditProperties; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; import org.onap.policy.pap.xacml.rest.controller.DecisionPolicyDictionaryController; @@ -80,70 +76,33 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletConfig; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; -import com.mockrunner.mock.web.MockServletInputStream; public class XACMLPAPTest { private static final Log logger = LogFactory.getLog(XACMLPAPTest.class); private static final String ENVIRONMENT_HEADER = "Environment"; - private List<String> headers = new ArrayList<>(); + private static List<String> headers = new ArrayList<>(); private HttpServletRequest httpServletRequest; private HttpServletResponse httpServletResponse; private ServletOutputStream mockOutput; - private ServletConfig servletConfig; - private XACMLPapServlet pap; - private SessionFactory sessionFactory; - private CommonClassDao commonClassDao; + private static ServletConfig servletConfig; + private static XACMLPapServlet pap; + private static SessionFactory sessionFactory; + private static CommonClassDao commonClassDao; private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; private static final String DEFAULT_DB_USER = "sa"; private static final String DEFAULT_DB_PWD = ""; - @Before - public void setUpDB() throws Exception { - logger.info("setUpDB: Entering"); - - Properties properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, XACMLPAPTest.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest"); - properties.put(IntegrityAuditProperties.DB_USER, XACMLPAPTest.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, XACMLPAPTest.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pap"); - - //Clean the iaTest DB table for IntegrityAuditEntity entries - cleanDb("testPapPU", properties); - - logger.info("setUpDB: Exiting"); - } - - public void cleanDb(String persistenceUnit, Properties properties) { - logger.debug("cleanDb: enter"); - - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // Clean up the DB - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - logger.debug("cleanDb: exit"); + @BeforeClass + public static void beforeClassSetup() throws ServletException { + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("xacmlpaptest"); + new FirewallConfigPolicy(new CommonClassDaoImpl()); + new DictionaryUtils(new CommonClassDaoImpl()); + setUp(); } - @Before - public void setUp() throws ServletException { - httpServletRequest = Mockito.mock(HttpServletRequest.class); - httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); - Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); - + public static void setUp() throws ServletException { servletConfig = Mockito.mock(MockServletConfig.class); System.setProperty("com.sun.management.jmxremote.port", "9993"); Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); @@ -154,59 +113,56 @@ public class XACMLPAPTest { commonClassDao = Mockito.mock(CommonClassDao.class); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); + UserInfo user = new UserInfo(); + user.setUserLoginId("API"); + user.setUserName("API"); + Mockito.when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "API")).thenReturn(user); Mockito.mock(DictionaryUtils.class); } + @Before + public void testInit() { + httpServletRequest = Mockito.mock(HttpServletRequest.class); + httpServletResponse = Mockito.mock(MockHttpServletResponse.class); + Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); + CommonClassDaoImpl.setSessionfactory(sessionFactory); + PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); + } + @Test public void testFirwallCreatePolicy() throws IOException, ServletException, SQLException { httpServletRequest = Mockito.mock(HttpServletRequest.class); - String json = - "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\"," + - "\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\"," + - "\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\"," + - "\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}]," + - "\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\"," + - "\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\"," + - "\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\"," + - "\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\"," + - "\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"]," + - "\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false," + - "\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}]," + - "\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[]," + - "\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\"," + - "\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true," + - "\"log\":true}]}"; + String json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\"," + + "\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\"," + + "\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\"," + + "\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}]," + + "\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\"," + + "\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\"," + + "\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\"," + + "\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\"," + + "\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"]," + + "\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false," + + "\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}]," + + "\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[]," + + "\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\"," + + "\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true," + + "\"log\":true}]}"; Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn("DEVL"); Mockito.when(httpServletRequest.getMethod()).thenReturn("PUT"); Mockito.when(httpServletRequest.getParameter("apiflag")).thenReturn("api"); Mockito.when(httpServletRequest.getParameter("operation")).thenReturn("create"); Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Config"); - StdPAPPolicy newPAPPolicy = - new StdPAPPolicy(StdPAPPolicyParams.builder() - .configPolicyType("Firewall Config") - .policyName("test") - .description("testDescription") - .configName("Test") - .editPolicy(false) - .domain("test") - .jsonBody(json) - .highestVersion(0) - .riskLevel("5") - .riskType("default") - .guard("false") - .ttlDate("") - .build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("Firewall Config") + .policyName("test").description("testDescription").configName("Test").editPolicy(false).domain("test") + .jsonBody(json).highestVersion(0).riskLevel("5").riskType("default").guard("false").ttlDate("") + .build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Config_FW_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -222,38 +178,19 @@ public class XACMLPAPTest { ruleAttributes.put("templateName", "testPolicy"); ruleAttributes.put("samPoll", "5"); ruleAttributes.put("value", "test"); - //Creating BRMS Param Policies from the Admin Console - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder() - .configPolicyType("BRMS_Param") - .policyName("test") - .description("testing") - .configName("BRMS_PARAM_RULE") - .editPolicy(false) - .domain("test") - .dynamicFieldConfigAttributes(matchingAttributes) - .highestVersion(0) - .onapName("DROOLS") - .configBodyData(null) - .drlRuleAndUIParams(ruleAttributes) - .riskLevel("5") - .riskType("default") - .guard("false") - .ttlDate("") - .brmsController(null) - .brmsDependency(null) - .build()); + // Creating BRMS Param Policies from the Admin Console + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("BRMS_Param") + .policyName("test").description("testing").configName("BRMS_PARAM_RULE").editPolicy(false) + .domain("test").dynamicFieldConfigAttributes(matchingAttributes).highestVersion(0).onapName("DROOLS") + .configBodyData(null).drlRuleAndUIParams(ruleAttributes).riskLevel("5").riskType("default") + .guard("false").ttlDate("").brmsController(null).brmsDependency(null).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); setPolicyCreation(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Config_BRMS_Param_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -266,33 +203,17 @@ public class XACMLPAPTest { Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Config"); Map<String, String> ruleAttributes = new HashMap<>(); ruleAttributes.put("value", "test"); - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder() - .configPolicyType("BRMS_Raw") - .policyName("test") - .description("testig description") - .configName("BRMS_RAW_RULE") - .editPolicy(false) - .domain("test") - .dynamicFieldConfigAttributes(ruleAttributes) - .highestVersion(0) - .onapName("DROOLS") - .configBodyData("test") - .riskLevel("4") - .riskType("default") - .guard("false") - .build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("BRMS_Raw") + .policyName("test").description("testig description").configName("BRMS_RAW_RULE").editPolicy(false) + .domain("test").dynamicFieldConfigAttributes(ruleAttributes).highestVersion(0).onapName("DROOLS") + .configBodyData("test").riskLevel("4").riskType("default").guard("false").build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); setPolicyCreation(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Config_BRMS_Raw_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -304,36 +225,18 @@ public class XACMLPAPTest { Mockito.when(httpServletRequest.getParameter("operation")).thenReturn("create"); Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Config"); String json = "{\"test\":\"java\"}"; - //Creating CloseLoop_Fault and Performance Metric Policies - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder() - .configPolicyType("ClosedLoop_PM") - .policyName("test") - .description("testing") - .onapName("onap") - .jsonBody(json) - .draft(false) - .oldPolicyFileName(null) - .serviceType("Registration Failure(Trinity)") - .editPolicy(false) - .domain("test") - .highestVersion(0) - .riskLevel(null) - .riskType("default") - .guard("true") - .ttlDate("") - .build()); + // Creating CloseLoop_Fault and Performance Metric Policies + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("ClosedLoop_PM") + .policyName("test").description("testing").onapName("onap").jsonBody(json).draft(false) + .oldPolicyFileName(null).serviceType("Registration Failure(Trinity)").editPolicy(false).domain("test") + .highestVersion(0).riskLevel(null).riskType("default").guard("true").ttlDate("").build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); setPolicyCreation(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Config_PM_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -344,26 +247,15 @@ public class XACMLPAPTest { Mockito.when(httpServletRequest.getParameter("apiflag")).thenReturn("api"); Mockito.when(httpServletRequest.getParameter("operation")).thenReturn("create"); Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Decision"); - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder() - .policyName("test") - .description("test rule") - .onapName("ONAP") - .providerComboBox("AAF") - .editPolicy(false) - .domain("test") - .highestVersion(0) - .build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy( + StdPAPPolicyParams.builder().policyName("test").description("test rule").onapName("ONAP") + .providerComboBox("AAF").editPolicy(false).domain("test").highestVersion(0).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Decision_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -384,31 +276,18 @@ public class XACMLPAPTest { matchingAttributes.put("timeUnits", "minute"); matchingAttributes.put("guardActiveStart", "05:00"); matchingAttributes.put("guardActiveEnd", "10:00"); - StdPAPPolicy newPAPPolicy = - - new StdPAPPolicy(StdPAPPolicyParams.builder() - .policyName("testGuard") - .description("test rule") - .onapName("PDPD") - .providerComboBox("GUARD_YAML") - .dynamicFieldConfigAttributes(matchingAttributes) - .editPolicy(false) - .domain("test") - .highestVersion(0) - .build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy( + StdPAPPolicyParams.builder().policyName("testGuard").description("test rule").onapName("PDPD") + .providerComboBox("GUARD_YAML").dynamicFieldConfigAttributes(matchingAttributes) + .editPolicy(false).domain("test").highestVersion(0).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Decision_testGuard.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } - + @Test public void testDecisonGuardMinMaxPolicy() throws IOException, ServletException, SQLException { httpServletRequest = Mockito.mock(HttpServletRequest.class); @@ -429,20 +308,15 @@ public class XACMLPAPTest { StdPAPPolicy newPAPPolicy = new StdPAPPolicy( - StdPAPPolicyParams.builder().policyName("testGuard").description("test rule").onapName("PDPD") + StdPAPPolicyParams.builder().policyName("testGuardMinMax").description("test rule").onapName("PDPD") .providerComboBox("GUARD_MIN_MAX").dynamicFieldConfigAttributes(matchingAttributes) .editPolicy(false).domain("test").highestVersion(0).build()); - MockServletInputStream mockInput = new MockServletInputStream( - PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); + MockServletInputStream mockInput = + new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Decision_testGuard.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @@ -461,28 +335,16 @@ public class XACMLPAPTest { matchingAttributes.put("guardActiveStart", "05:00"); matchingAttributes.put("guardActiveEnd", "10:00"); matchingAttributes.put("blackList", "bl1,bl2"); - StdPAPPolicy newPAPPolicy = - new StdPAPPolicy(StdPAPPolicyParams.builder() - .policyName("testblGuard") - .description("test rule") - .onapName("PDPD") - .providerComboBox("GUARD_BL_YAML") - .dynamicFieldConfigAttributes(matchingAttributes) - .editPolicy(false) - .domain("test") - .highestVersion(0) - .build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy( + StdPAPPolicyParams.builder().policyName("testblGuard").description("test rule").onapName("PDPD") + .providerComboBox("GUARD_BL_YAML").dynamicFieldConfigAttributes(matchingAttributes) + .editPolicy(false).domain("test").highestVersion(0).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Decision_testblGuard.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } @Test @@ -495,33 +357,17 @@ public class XACMLPAPTest { Mockito.when(httpServletRequest.getParameter("policyType")).thenReturn("Config"); Map<String, String> configAttributes = new HashMap<>(); configAttributes.put("value", "test"); - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder() - .configPolicyType("Base") - .policyName("test") - .description("test rule") - .onapName("TEST") - .configName("config") - .dynamicFieldConfigAttributes(configAttributes) - .configType("OTHER") - .configBodyData("test body") - .editPolicy(false) - .domain("test") - .highestVersion(0) - .riskLevel("5") - .riskType("default") - .guard("false") - .ttlDate(null).build()); + StdPAPPolicy newPAPPolicy = new StdPAPPolicy( + StdPAPPolicyParams.builder().configPolicyType("Base").policyName("test").description("test rule") + .onapName("TEST").configName("config").dynamicFieldConfigAttributes(configAttributes) + .configType("OTHER").configBodyData("test body").editPolicy(false).domain("test") + .highestVersion(0).riskLevel("5").riskType("default").guard("false").ttlDate(null).build()); MockServletInputStream mockInput = new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - // set DBDao - setDBDao(); pap.service(httpServletRequest, httpServletResponse); - - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - Mockito.verify(httpServletResponse).addHeader("successMapKey", "success"); - Mockito.verify(httpServletResponse).addHeader("policyName", "test.Config_test.1.xml"); + Mockito.verify(httpServletResponse).addHeader("operation", "create"); } private void setPolicyCreation() { @@ -539,30 +385,14 @@ public class XACMLPAPTest { BRMSParamTemplate template = new BRMSParamTemplate(); template.setRuleName("testPolicy"); template.setUserCreatedBy(userInfo); - String rule = "package com.sample;\n" - + "import com.sample.DroolsTest.Message;\n" - + "declare Params\n" - + "samPoll : int\n" - + "value : String\n" - + "end\n" - + "///This Rule will be generated by the UI.\n" - + "rule \"${policyName}.Create parameters structure\"\n" - + "salience 1000 \n" - + "when\n" - + "then\n" - + "Params params = new Params();\n" - + "params.setSamPoll(76);\n" - + "params.setValue(\"test\");\n" - + "insertLogical(params);\n" - + "end\n" - + "rule \"Rule 1: Check parameter structure access from when/then\"\n" - + "when\n" - + "$param: Params()\n" - + "Params($param.samPoll > 50)\n" - + "then\n" - + "System.out.println(\"Firing rule 1\");\n" - + "System.out.println($param);\n" - + "end\n"; + String rule = "package com.sample;\n" + "import com.sample.DroolsTest.Message;\n" + "declare Params\n" + + "samPoll : int\n" + "value : String\n" + "end\n" + "///This Rule will be generated by the UI.\n" + + "rule \"${policyName}.Create parameters structure\"\n" + "salience 1000 \n" + "when\n" + "then\n" + + "Params params = new Params();\n" + "params.setSamPoll(76);\n" + "params.setValue(\"test\");\n" + + "insertLogical(params);\n" + "end\n" + + "rule \"Rule 1: Check parameter structure access from when/then\"\n" + "when\n" + "$param: Params()\n" + + "Params($param.samPoll > 50)\n" + "then\n" + "System.out.println(\"Firing rule 1\");\n" + + "System.out.println($param);\n" + "end\n"; template.setRule(rule); Mockito.when(commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", "testPolicy")) .thenReturn(template); @@ -572,14 +402,14 @@ public class XACMLPAPTest { @Test public void testClosedLoopCreateDictionary() throws IOException, SQLException, ServletException { httpServletRequest = Mockito.mock(HttpServletRequest.class); - // Check VSCLAction. + // Check VSCLAction. String json = "{\"dictionaryFields\": {\"vsclaction\": \"testRestAPI\",\"description\": \"testing create\"}}"; dictionaryTestSetup(false, "VSCLAction", json); // set DBDao ClosedLoopDictionaryController.setCommonClassDao(new CommonClassDaoImpl()); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check VNFType @@ -590,34 +420,32 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "VNFType", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check PEPOptions // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"pepName\":\"testRestAPI\",\"description\":\"testing create\"," + - "\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + - "\"number\":\"test\"}]}}"; + json = "{\"dictionaryFields\":{\"pepName\":\"testRestAPI\",\"description\":\"testing create\"," + + "\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + + "\"number\":\"test\"}]}}"; dictionaryTestSetup(false, "PEPOptions", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check Varbind // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"varbindName\":\"testRestAPI\",\"varbindDescription\":\"testing\"," + - "\"varbindOID\":\"test\"}}"; + json = "{\"dictionaryFields\":{\"varbindName\":\"testRestAPI\",\"varbindDescription\":\"testing\"," + + "\"varbindOID\":\"test\"}}"; dictionaryTestSetup(false, "Varbind", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check Service @@ -628,7 +456,7 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "Service", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check Site @@ -639,21 +467,21 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "Site", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); } @Test public void testFirewallCreateDictionary() throws IOException, SQLException, ServletException { httpServletRequest = Mockito.mock(HttpServletRequest.class); - // Check SecurityZone. + // Check SecurityZone. String json = "{\"dictionaryFields\":{\"zoneName\":\"testRestAPI\",\"zoneValue\":\"testing\"}}"; dictionaryTestSetup(false, "SecurityZone", json); // set DBDao FirewallDictionaryController.setCommonClassDao(new CommonClassDaoImpl()); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // // Check Action List @@ -664,10 +492,10 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "ActionList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check Protocol List. + // Check Protocol List. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); @@ -675,10 +503,10 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "ProtocolList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check Zone. + // Check Zone. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); @@ -686,81 +514,76 @@ public class XACMLPAPTest { dictionaryTestSetup(false, "Zone", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check PrefixList. + // Check PrefixList. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"prefixListName\":\"testRestAPI\",\"prefixListValue\":\"127.0.0.1\"," + - "\"description\":\"testing\"}}"; + json = "{\"dictionaryFields\":{\"prefixListName\":\"testRestAPI\",\"prefixListValue\":\"127.0.0.1\"," + + "\"description\":\"testing\"}}"; dictionaryTestSetup(false, "PrefixList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check AddressGroup. + // Check AddressGroup. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"groupName\":\"testRestAPIgroup\",\"description\":\"testing\"," + - "\"attributes\":[{\"option\":\"testRestAPI\"}, {\"option\":\"testRestAPI\"}]}}"; + json = "{\"dictionaryFields\":{\"groupName\":\"testRestAPIgroup\",\"description\":\"testing\"," + + "\"attributes\":[{\"option\":\"testRestAPI\"}, {\"option\":\"testRestAPI\"}]}}"; dictionaryTestSetup(false, "AddressGroup", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check ServiceGroup. + // Check ServiceGroup. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"groupName\":\"testRestAPIServiceGroup\"," + - "\"attributes\":[{\"option\":\"testRestAPIservice\"}]}}"; + json = "{\"dictionaryFields\":{\"groupName\":\"testRestAPIServiceGroup\"," + + "\"attributes\":[{\"option\":\"testRestAPIservice\"}]}}"; dictionaryTestSetup(false, "ServiceGroup", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check ServiceList. + // Check ServiceList. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"serviceName\":\"testRestAPIservice\",\"serviceDescription\":\"test\"," + - "\"servicePorts\":\"8888\",\"transportProtocols\":[{\"option\":\"testRestAPI\"}," + - "{\"option\":\"testRestAPI1\"}],\"appProtocols\":[{\"option\":\"testRestAPI\"}," + - "{\"option\":\"testRestAPI1\"}]}}"; + json = "{\"dictionaryFields\":{\"serviceName\":\"testRestAPIservice\",\"serviceDescription\":\"test\"," + + "\"servicePorts\":\"8888\",\"transportProtocols\":[{\"option\":\"testRestAPI\"}," + + "{\"option\":\"testRestAPI1\"}],\"appProtocols\":[{\"option\":\"testRestAPI\"}," + + "{\"option\":\"testRestAPI1\"}]}}"; dictionaryTestSetup(false, "ServiceList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check TermList. + // Check TermList. // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"termName\":\"testRestAPIRule\",\"termDescription\":\"testing\"," + - "\"fromZoneDatas\":[{\"option\":\"testRestAPI\"}]," + - "\"toZoneDatas\":[{\"option\":\"testRestAPI1\"}]," + - "\"sourceListDatas\":[{\"option\":\"Group_testportal\"}]," + - "\"destinationListDatas\":[{\"option\":\"testRestAPI\"}]," + - "\"sourceServiceDatas\":[{\"option\":\"testRestAPIservice\"}," + - "{\"option\":\"testRestAPIservice1\"}]," + - "\"destinationServiceDatas\":[{\"option\":\"testRestAPIservice1\"}," + - "{\"option\":\"testportalservice2\"}],\"actionListDatas\":[{\"option\":\"testRestAPI\"}]}}"; + json = "{\"dictionaryFields\":{\"termName\":\"testRestAPIRule\",\"termDescription\":\"testing\"," + + "\"fromZoneDatas\":[{\"option\":\"testRestAPI\"}]," + + "\"toZoneDatas\":[{\"option\":\"testRestAPI1\"}]," + + "\"sourceListDatas\":[{\"option\":\"Group_testportal\"}]," + + "\"destinationListDatas\":[{\"option\":\"testRestAPI\"}]," + + "\"sourceServiceDatas\":[{\"option\":\"testRestAPIservice\"}," + + "{\"option\":\"testRestAPIservice1\"}]," + + "\"destinationServiceDatas\":[{\"option\":\"testRestAPIservice1\"}," + + "{\"option\":\"testportalservice2\"}],\"actionListDatas\":[{\"option\":\"testRestAPI\"}]}}"; dictionaryTestSetup(false, "TermList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); - // Verify + // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); } @@ -776,8 +599,8 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); String json = - "{\"dictionaryFields\": {\"onapName\": \"testMMRestAPI1\",\"description\": \"testing update response " + - "message\"}}"; + "{\"dictionaryFields\": {\"onapName\": \"testMMRestAPI1\",\"description\": \"testing update response " + + "message\"}}"; dictionaryTestSetup(false, "OnapName", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -786,11 +609,10 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\": {\"xacmlId\": \"testMMRestAPI1\",\"datatypeBean\": {\"shortName\": " + - "\"string\"}, \"description\": \"testing update\",\"priority\": \"High\"," + - "\"userDataTypeValues\": [{\"attributeValues\": \"testAttr\"}, {\"attributeValues\": " + - "\"testAttr2\"}, {\"attributeValues\": \"testAttr3\"}]}}"; + json = "{\"dictionaryFields\": {\"xacmlId\": \"testMMRestAPI1\",\"datatypeBean\": {\"shortName\": " + + "\"string\"}, \"description\": \"testing update\",\"priority\": \"High\"," + + "\"userDataTypeValues\": [{\"attributeValues\": \"testAttr\"}, {\"attributeValues\": " + + "\"testAttr2\"}, {\"attributeValues\": \"testAttr3\"}]}}"; dictionaryTestSetup(false, "Attribute", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -800,11 +622,10 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl" + - ".com\",\"method\":\"GET\",\"description\":\"test create\",\"body\":\"Testing Create\"," + - "\"headers\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + - "\"number\":\"test\"}]}}"; + json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl" + + ".com\",\"method\":\"GET\",\"description\":\"test create\",\"body\":\"Testing Create\"," + + "\"headers\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + + "\"number\":\"test\"}]}}"; dictionaryTestSetup(false, "Action", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -813,10 +634,9 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"scopeName\":\"testMMRestAPI1\",\"description\":\"test\"," + - "\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + - "\"number\":\"test\"}]}}"; + json = "{\"dictionaryFields\":{\"scopeName\":\"testMMRestAPI1\",\"description\":\"test\"," + + "\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\"," + + "\"number\":\"test\"}]}}"; dictionaryTestSetup(false, "DescriptiveScope", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -834,9 +654,8 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"message\":\"test\"," + - "\"riskType\":\"testMMrestAPI1\"}}"; + json = "{\"dictionaryFields\":{\"name\":\"testMMrestAPI1\",\"message\":\"test\"," + + "\"riskType\":\"testMMrestAPI1\"}}"; dictionaryTestSetup(false, "SafePolicyWarning", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -850,8 +669,8 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); String json = - "{\"dictionaryFields\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"}," + - "\"description\":\"test\",\"priority\":\"High\"}}"; + "{\"dictionaryFields\":{\"xacmlId\":\"testMMRestAPI1\",\"datatypeBean\":{\"shortName\":\"string\"}," + + "\"description\":\"test\",\"priority\":\"High\"}}"; dictionaryTestSetup(false, "Settings", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -860,9 +679,8 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"bbid\":\"BB1\",\"workstep\":\"1\",\"treatments\":\"Manual Handling,Abort," + - "Retry\"}}"; + json = "{\"dictionaryFields\":{\"bbid\":\"BB1\",\"workstep\":\"1\",\"treatments\":\"Manual Handling,Abort," + + "Retry\"}}"; dictionaryTestSetup(false, "RainyDayTreatments", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -939,10 +757,9 @@ public class XACMLPAPTest { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - json = - "{\"dictionaryFields\":{\"groupName\":\"testMMrestAPI1\",\"description\":\"testing\"}," + - "\"groupPolicyScopeListData1\":{\"resource\":\"ANY\",\"type\":\"ANY\",\"service\":\"ANY\"," + - "\"closedloop\":\"ANY\"}}"; + json = "{\"dictionaryFields\":{\"groupName\":\"testMMrestAPI1\",\"description\":\"testing\"}," + + "\"groupPolicyScopeListData1\":{\"resource\":\"ANY\",\"type\":\"ANY\",\"service\":\"ANY\"," + + "\"closedloop\":\"ANY\"}}"; dictionaryTestSetup(false, "GroupPolicyScopeList", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); @@ -965,8 +782,6 @@ public class XACMLPAPTest { MockServletInputStream mockInput = new MockServletInputStream(json.getBytes()); Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); Mockito.when(httpServletRequest.getReader()).thenReturn(new BufferedReader(new InputStreamReader(mockInput))); - // set DBDao - setDBDao(); } public void setDBDao() throws SQLException { @@ -995,13 +810,13 @@ public class XACMLPAPTest { @Test public void getDictionary() throws ServletException, IOException { - String[] dictionarys = new String[]{"Attribute", "OnapName", "Action", "BRMSParamTemplate", "VSCLAction" - , "VNFType", "PEPOptions", "Varbind", "Service", "Site", "Settings", "RainyDayTreatments", - "DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone", - "PrefixList", "AddressGroup", "ServiceGroup", "ServiceList", "TermList", - "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID", "MicroServiceModels", - "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType", "PolicyScopeClosedLoop", - "GroupPolicyScopeList", "RiskType", "SafePolicyWarning", "MicroServiceDictionary"}; + String[] dictionarys = new String[] {"Attribute", "OnapName", "Action", "BRMSParamTemplate", "VSCLAction", + "VNFType", "PEPOptions", "Varbind", "Service", "Site", "Settings", "RainyDayTreatments", + "DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone", "PrefixList", "AddressGroup", + "ServiceGroup", "ServiceList", "TermList", "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID", + "MicroServiceModels", "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType", + "PolicyScopeClosedLoop", "GroupPolicyScopeList", "RiskType", "SafePolicyWarning", + "MicroServiceDictionary"}; for (String dictionary : dictionarys) { httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = new MockHttpServletResponse(); @@ -1034,8 +849,8 @@ public class XACMLPAPTest { } } - @After - public void destroy() { + @AfterClass + public static void destroy() { if (sessionFactory != null) { sessionFactory.close(); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java index 3cf3128dd..ec9229c71 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-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. @@ -17,18 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; - +import com.att.research.xacml.util.XACMLProperties; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -37,8 +37,6 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.adapter.RainyDayParams; -import com.att.research.xacml.util.XACMLProperties; - public class DecisionPolicyTest { private static Logger logger = FlexLogger.getLogger(DecisionPolicyTest.class); @@ -99,7 +97,7 @@ public class DecisionPolicyTest { policyAdapter.setRainydayMap(treatmentMap); policyAdapter.setRainyday(rainyday); - component = new DecisionPolicy(policyAdapter, null); + component = new DecisionPolicy(policyAdapter); logger.info("setUp: exit"); } @@ -131,7 +129,7 @@ public class DecisionPolicyTest { public void testPrepareToSaveRainyDay() { logger.debug("test PrepareToSave Policy: enter"); policyAdapter.setRuleProvider("Rainy_Day"); - component = new DecisionPolicy(policyAdapter, null); + component = new DecisionPolicy(policyAdapter); boolean response = false; try { @@ -141,4 +139,4 @@ public class DecisionPolicyTest { } assertTrue(response); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java index f7dd92a3e..0e89a7085 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,82 +21,65 @@ package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.fail; - +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.XACMLProperties; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; +import java.util.Properties; import javax.persistence.PersistenceException; -import javax.persistence.Query; - import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Ignore; 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.pap.xacml.rest.DataToNotifyPdp; import org.onap.policy.pap.xacml.rest.components.PolicyDBDao.PolicyDBDaoTestClass; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.jpa.DatabaseLockEntity; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdEngine; import org.onap.policy.xacml.std.pap.StdPDPGroup; -import org.onap.policy.xacml.util.XACMLPolicyWriter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.XACMLProperties; - +import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -public class PolicyDBDaoTest extends Mockito{ - +public class PolicyDBDaoTest { private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class); - PolicyDBDaoTestClass d; - PolicyDBDao dbd; - PolicyDBDao dbd2; - EntityManagerFactory emf; - private Path repository; - StdEngine stdEngine = null; - - @Before - public void init() throws PAPException, IOException{ - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties"); - emf = Persistence.createEntityManagerFactory("testPapPU"); - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - try{ - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - em.createQuery("DELETE FROM PdpEntity").executeUpdate(); - em.createQuery("DELETE FROM GroupEntity").executeUpdate(); - - em.getTransaction().commit(); - } catch(Exception e){ - logger.error("Exception Occured"+e); - em.getTransaction().rollback(); - } - em.close(); + static PolicyDBDaoTestClass d; + static PolicyDBDao dbd; + static PolicyDBDao dbd2; + private static Path repository; + static StdEngine stdEngine = null; + static SessionFactory sessionFactory = null; + + @BeforeClass + public static void init() throws PAPException, IOException { + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); try { - dbd = PolicyDBDao.getPolicyDBDaoInstance(emf); - dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf); + sessionFactory = setupH2DbDaoImpl("testdbdao"); + dbd = PolicyDBDao.getPolicyDBDaoInstance(); + dbd2 = PolicyDBDao.getPolicyDBDaoInstance(); } catch (Exception e) { Assert.fail(); } @@ -109,41 +92,76 @@ public class PolicyDBDaoTest extends Mockito{ } @After - public void cleanUp(){ - PolicyDBDao.setJunit(false); - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - try{ - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - em.createQuery("DELETE FROM PdpEntity").executeUpdate(); - em.createQuery("DELETE FROM GroupEntity").executeUpdate(); - - em.getTransaction().commit(); - } catch(Exception e){ - em.getTransaction().rollback(); - } - em.close(); + public void cleanUp() { try { FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory")); } catch (IOException e) { - //could not delete + // could not delete } } + public static SessionFactory setupH2DbDaoImpl(String dbName) { + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + dataSource.setUrl("jdbc:h2:mem:" + dbName + ";DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); + dataSource.setUsername("sa"); + dataSource.setPassword(""); + LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); + sessionBuilder.scanPackages("org.onap.*"); + + Properties properties = new Properties(); + properties.put("hibernate.show_sql", "false"); + properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + properties.put("hibernate.hbm2ddl.auto", "create-drop"); + + sessionBuilder.addProperties(properties); + SessionFactory sessionFac = sessionBuilder.buildSessionFactory(); + + new PolicyDBDao(sessionFac); + new PolicyDbDaoTransactionInstance(sessionFac).isJunit = true; + CommonClassDaoImpl.setSessionfactory(sessionFac); + new DataToNotifyPdp(new CommonClassDaoImpl()); + PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); + + DatabaseLockEntity lock = null; + Session session = sessionFac.openSession(); + session.getTransaction().begin(); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1); + if (lock == null) { + lock = new DatabaseLockEntity(); + lock.setKey(1); + session.persist(lock); + session.flush(); + } + session.getTransaction().commit(); + session.close(); + + UserInfo user = new UserInfo(); + user.setUserLoginId("API"); + user.setUserName("API"); + Session session2 = sessionFac.openSession(); + session2.getTransaction().begin(); + session2.persist(user); + + session2.getTransaction().commit(); + session2.close(); + + return sessionFac; + } + + @Test - public void getConfigFileTest(){ + public void testGetConfigFile() { PolicyRestAdapter pra = new PolicyRestAdapter(); pra.setConfigType(ConfigPolicy.JSON_CONFIG); String configFile = d.getConfigFile("Config_mypolicy.xml", "org.onap", pra); Assert.assertEquals("org.onap.Config_mypolicy.json", configFile); - //yes, we can do action files too even though they don't have configs + // yes, we can do action files too even though they don't have configs configFile = d.getConfigFile("Action_mypolicy.xml", "org.onap", pra); Assert.assertEquals("org.onap.Action_mypolicy.json", configFile); } - + @Test public void getPolicyNameAndVersionFromPolicyFileNameTest() throws PolicyDBException { String policyName = "com.Decision_testname.1.xml"; @@ -153,7 +171,7 @@ public class PolicyDBDaoTest extends Mockito{ String[] actualNameAndVersion = d.getPolicyNameAndVersionFromPolicyFileName(policyName); Assert.assertArrayEquals(expectedNameAndVersion, actualNameAndVersion); } - + @Test public void getNameScopeAndVersionFromPdpPolicyTest() { String fileName = "com.Decision_testname.1.xml"; @@ -161,32 +179,33 @@ public class PolicyDBDaoTest extends Mockito{ expectedArray[0] = "Decision_testname.1.xml"; expectedArray[2] = "1"; expectedArray[1] = "com"; - + String[] returnArray = d.getNameScopeAndVersionFromPdpPolicy(fileName); Assert.assertArrayEquals(expectedArray, returnArray); } - + @Test public void getPdpPolicyNameTest() { String name = "Decision_testname.1.json"; String scope = "com"; String expectedFinalname = "com.Decision_testname.1.xml"; - + String finalname = d.getPdpPolicyName(name, scope); Assert.assertEquals(expectedFinalname, finalname); } - + @Test public void getPolicySubFileTest() { String name = "Config_testname.1.json"; String subFileType = "Config"; - - Path path = d.getPolicySubFile(name, subFileType); + HandleIncomingNotifications handle = new HandleIncomingNotifications(sessionFactory); + + Path path = handle.getPolicySubFile(name, subFileType); Assert.assertNull(path); } @Test - public void createFromPolicyObject(){ + public void createFromPolicyObject() { Policy policyObject = new ConfigPolicy(); policyObject.policyAdapter = new PolicyRestAdapter(); policyObject.policyAdapter.setConfigName("testpolicy1"); @@ -202,37 +221,45 @@ public class PolicyDBDaoTest extends Mockito{ policyObject.policyAdapter.setPolicyData(policyTypeObject); ClassLoader classLoader = getClass().getClassLoader(); PolicyType policyConfig = new PolicyType(); - policyConfig.setVersion(Integer.toString(1)); + policyConfig.setVersion("1"); policyConfig.setPolicyId(""); policyConfig.setTarget(new TargetType()); policyObject.policyAdapter.setData(policyConfig); - mock(XACMLPolicyWriter.class); try { - policyObject.policyAdapter.setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"))); + policyObject.policyAdapter + .setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"))); } catch (Exception e2) { fail(); } PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); - try{ + try { transaction.createPolicy(policyObject, "testuser1"); transaction.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { transaction.rollbackTransaction(); Assert.fail(); } - EntityManager getData = emf.createEntityManager(); - Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name"); - getDataQuery.setParameter("scope", "com"); - getDataQuery.setParameter("name","Config_SampleTest1206.1.xml"); + Session session = sessionFactory.openSession(); + session.getTransaction().begin(); + Query policyQuery = + session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); + + policyQuery.setParameter("name", "Config_SampleTest1206.1.xml"); + policyQuery.setParameter("scope", "com"); + + List<?> policyQueryList = policyQuery.list(); PolicyEntity result = null; - try{ - result = (PolicyEntity)getDataQuery.getSingleResult(); - } catch(Exception e){ - logger.error("Exception Occured"+e); + try { + result = (PolicyEntity) policyQueryList.get(0); + } catch (Exception e) { + logger.error("Exception Occured " + e); Assert.fail(); } + session.getTransaction().commit(); + session.close(); + String expectedData; try { expectedData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); @@ -240,405 +267,428 @@ public class PolicyDBDaoTest extends Mockito{ expectedData = ""; } Assert.assertEquals(expectedData, result.getPolicyData()); - getData.close(); result = null; - transaction.commitTransaction(); Assert.assertFalse(transaction.isTransactionOpen()); } @Test - public void groupTransactions(){ + public void groupTransactions() { PolicyDBDaoTransaction group = dbd.getNewTransaction(); String groupName = "test group 1"; - try{ - group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser"); + try { + group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group", + "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - EntityManager em = emf.createEntityManager(); - Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + Session session = sessionFactory.openSession(); + session.getTransaction().begin(); + Query getGroup = + session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); getGroup.setParameter("deleted", false); - List<?> groups = getGroup.getResultList(); - if(groups.size() != 1){ - Assert.fail(); - } - GroupEntity groupEntity = (GroupEntity)groups.get(0); - em.close(); + List<?> groups = getGroup.list(); + GroupEntity groupEntity = (GroupEntity) groups.get(0); Assert.assertEquals(groupName, groupEntity.getgroupName()); Assert.assertEquals("this is a test group", groupEntity.getDescription()); + session.getTransaction().commit(); + session.close(); + group = dbd.getNewTransaction(); - try{ - OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/")); - group.deleteGroup(groupToDelete, null,"testuser"); + try { + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName), Paths.get("/")); + group.deleteGroup(groupToDelete, null, "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); + Session session2 = sessionFactory.openSession(); + session2.getTransaction().begin(); + Query getGroup2 = + session2.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup2.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); + getGroup2.setParameter("deleted", false); + List<?> groups2 = getGroup2.list(); + groups2 = getGroup2.list(); + if (groups2.size() != 0) { + System.out.println("Group size: " + groups2.size()); Assert.fail(); } - em.close(); - //add a pdp to a group + session2.getTransaction().commit(); + session2.close(); + + + // add a pdp to a group group = dbd.getNewTransaction(); - try{ + try { group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } + group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser"); + try { + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", + "the main pdp", 3232, "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - em = emf.createEntityManager(); - Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + + Session session3 = sessionFactory.openSession(); + session3.getTransaction().begin(); + Query getPdp = session3.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); getPdp.setParameter("deleted", false); - List<?> pdps = getPdp.getResultList(); - if(pdps.size() != 1){ - System.out.println("Group size: "+pdps.size()); + List<?> pdps = getPdp.list(); + if (pdps.size() != 1) { + System.out.println("Group size: " + pdps.size()); Assert.fail(); } - PdpEntity pdp = (PdpEntity)pdps.get(0); + PdpEntity pdp = (PdpEntity) pdps.get(0); Assert.assertEquals(groupName, pdp.getGroup().getgroupName()); Assert.assertEquals(pdp.getPdpName(), "primary"); - em.close(); + session3.getTransaction().commit(); + session3.close(); + + group = dbd.getNewTransaction(); - try{ - group.removePdpFromGroup("http://localhost:4344/pdp/","testuser"); + try { + group.removePdpFromGroup("http://localhost:4344/pdp/", "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - if(pdps.size() != 0){ - System.out.println("Group size: "+pdps.size()); + + Session session4 = sessionFactory.openSession(); + session4.getTransaction().begin(); + Query getPdp2 = session4.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + getPdp2.setParameter("pdpId", "http://localhost:4344/pdp/"); + getPdp2.setParameter("deleted", false); + List<?> pdps2 = getPdp2.list(); + if (pdps2.size() != 0) { + System.out.println("Group size: " + pdps2.size()); Assert.fail(); } - em.close(); - //add some pdps to groups + session4.getTransaction().commit(); + session4.close(); + + // add some pdps to groups group = dbd.getNewTransaction(); - try{ + try { group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } group = dbd.getNewTransaction(); - try{ + try { group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser"); + try { + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", + "the main pdp", 3232, "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser"); + try { + group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), + "secondary", "the second pdp", 3233, "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - for(Object o : pdps){ - Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName()); + + Session session5 = sessionFactory.openSession(); + session5.getTransaction().begin(); + Query getPdp3 = session5.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); + getPdp3.setParameter("deleted", false); + List<?> pdps3 = getPdp3.list(); + for (Object obj : pdps3) { + Assert.assertEquals("testgroup1", ((PdpEntity) obj).getGroup().getgroupName()); } - em.close(); + + session5.getTransaction().commit(); + session5.close(); + group = dbd.getNewTransaction(); - try{ - OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/")); - OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); - group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); + try { + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), Paths.get("/")); + OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/")); + group.deleteGroup(groupToDelete, groupToMoveTo, "testuser"); group.commitTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "testgroup1"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); + + Session session6 = sessionFactory.openSession(); + session6.getTransaction().begin(); + Query getGroup3 = + session6.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup3.setParameter("groupId", "testgroup1"); + getGroup3.setParameter("deleted", false); + List<?> groups3 = getGroup3.list(); + if (groups3.size() != 0) { + System.out.println("Group size: " + groups3.size()); Assert.fail(); } - em.close(); - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - for(Object o : pdps){ - Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName()); + session6.getTransaction().commit(); + session6.close(); + + Session session7 = sessionFactory.openSession(); + session7.getTransaction().begin(); + Query getPdp4 = session7.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); + getPdp4.setParameter("deleted", false); + List<?> pdps4 = getPdp4.list(); + for (Object obj : pdps4) { + Assert.assertEquals("testgroup2", ((PdpEntity) obj).getGroup().getgroupName()); } - em.close(); + + session7.getTransaction().commit(); + session7.close(); + group = dbd.getNewTransaction(); - try{ - OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); + try { + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/")); OnapPDPGroup groupToMoveTo = null; - group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); + group.deleteGroup(groupToDelete, groupToMoveTo, "testuser"); group.commitTransaction(); Assert.fail(); - } catch(PolicyDBException pe){ - //good, can't delete group with pdps + } catch (PolicyDBException pe) { + // good, can't delete group with pdps group.rollbackTransaction(); - } catch(Exception e){ + } catch (Exception e) { group.rollbackTransaction(); - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - //update group - OnapPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/")); + // update group + OnapPDPGroup pdpGroup = + new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/")); group = dbd.getNewTransaction(); - try{ - group.updateGroup(pdpGroup, "testuser"); + try { + group.updateGroup(pdpGroup, "testuser", "testuser"); group.commitTransaction(); - }catch (Exception e){ - logger.error("Exception Occured"+e); + } catch (Exception e) { + logger.error("Exception Occured" + e); group.rollbackTransaction(); Assert.fail(); } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "newtestgroup2"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 1){ - System.out.println("Group size: "+groups.size()); + + Session session8 = sessionFactory.openSession(); + session8.getTransaction().begin(); + Query getGroup4 = + session8.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup4.setParameter("groupId", "newtestgroup2"); + getGroup4.setParameter("deleted", false); + List<?> groups4 = getGroup4.list(); + if (groups4.size() != 1) { + System.out.println("Group size: " + groups4.size()); Assert.fail(); } - em.close(); - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "testgroup2"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); + + session8.getTransaction().commit(); + session8.close(); + + Session session9 = sessionFactory.openSession(); + session9.getTransaction().begin(); + Query getGroup5 = + session9.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup5.setParameter("groupId", "testgroup2"); + getGroup5.setParameter("deleted", false); + List<?> groups5 = getGroup5.list(); + if (groups5.size() != 0) { + System.out.println("Group size: " + groups5.size()); Assert.fail(); } - em.close(); + + session9.getTransaction().commit(); + session9.close(); } @Ignore @Test - public void threadingStabilityTest(){ - if(logger.isDebugEnabled()){ - logger.debug("\n\n****************************" - + "threadingStabilityTest() entry" + public void threadingStabilityTest() { + if (logger.isDebugEnabled()) { + logger.debug("\n\n****************************" + "threadingStabilityTest() entry" + "******************************\n\n"); } PolicyDBDaoTransaction t = dbd.getNewTransaction(); Assert.assertTrue(t.isTransactionOpen()); try { - //Add 1000 ms to the timeout just to be sure it actually times out - int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n sleepTime = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + // Add 1000 ms to the timeout just to be sure it actually times out + int sleepTime = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n sleepTime = " + sleepTime + + "\n TimeStamp = " + date.getTime() + "\n\n"); } Thread.sleep(sleepTime); } catch (InterruptedException e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug( + "\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertFalse(t.isTransactionOpen() = " + + t.isTransactionOpen() + ")" + "\n TimeStamp = " + date.getTime() + "\n\n"); } Assert.assertFalse(t.isTransactionOpen()); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n a = dbd.getNewTransaction() " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n a = dbd.getNewTransaction() " + + "\n TimeStamp = " + date.getTime() + "\n\n"); } PolicyDBDaoTransaction a = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug( + "\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertTrue(a.isTransactionOpen() = " + + a.isTransactionOpen() + ")" + "\n TimeStamp = " + date.getTime() + "\n\n"); } Assert.assertTrue(a.isTransactionOpen()); try { - //Add 1000 ms to the timeout just to be sure it actually times out - int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n sleepTime = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + // Add 1000 ms to the timeout just to be sure it actually times out + int sleepTime = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n sleepTime = " + sleepTime + + "\n TimeStamp = " + date.getTime() + "\n\n"); } Thread.sleep(sleepTime); } catch (InterruptedException e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n b = dbd.getNewTransaction() " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n b = dbd.getNewTransaction() " + + "\n TimeStamp = " + date.getTime() + "\n\n"); } PolicyDBDaoTransaction b = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug( + "\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertFalse(a.isTransactionOpen() = " + + a.isTransactionOpen() + ")" + "\n TimeStamp = " + date.getTime() + "\n\n"); } Assert.assertFalse(a.isTransactionOpen()); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug( + "\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertTrue(b.isTransactionOpen() = " + + b.isTransactionOpen() + ")" + "\n TimeStamp = " + date.getTime() + "\n\n"); } Assert.assertTrue(b.isTransactionOpen()); b.close(); - //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms - System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000"); - //And let's lengthen the transaction timeout to 5000 ms - System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000"); - //get a transacton + // Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms + System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT, "1000"); + // And let's lengthen the transaction timeout to 5000 ms + System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT, "5000"); + // get a transacton PolicyDBDaoTransaction t1 = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug( + "\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertTrue(t1.isTransactionOpen() = " + + t1.isTransactionOpen() + ")" + "\n TimeStamp = " + date.getTime() + "\n\n"); } Assert.assertTrue(t1.isTransactionOpen()); - //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment - //but will collide at the DB. Remember that the wait time is only 1000 ms + // while it is open, get another from a different DB Dao so it will not collide on the synchronized + // code segment + // but will collide at the DB. Remember that the wait time is only 1000 ms try { - //Now the 2nd transaction has a wait timeout in 1000 ms + // Now the 2nd transaction has a wait timeout in 1000 ms PolicyDBDaoTransaction t2 = dbd2.getNewTransaction(); /* - * Give it plenty of time to time out the second transaction - * It will actually hang right here until it either gets the lock from the DB or the - * request for the DB lock times out. The timers are very sloppy so, I have given - * this plenty of leeway. + * Give it plenty of time to time out the second transaction It will actually hang right here until + * it either gets the lock from the DB or the request for the DB lock times out. The timers are very + * sloppy so, I have given this plenty of leeway. */ - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Thread.sleep(3000)" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Thread.sleep(3000)" + + "\n TimeStamp = " + date.getTime() + "\n\n"); } Thread.sleep(3000); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + + "\n TimeStamp = " + date.getTime() + "\n\n"); } - //Assert.assertTrue(t1.isTransactionOpen()); - //Assert.assertFalse(t2.isTransactionOpen()); + // Assert.assertTrue(t1.isTransactionOpen()); + // Assert.assertFalse(t2.isTransactionOpen()); Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n"); } catch (PersistenceException e) { - //success - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); + // success + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n SUCCESS! Transaction Wait Timeout worked!" - + "\n Caught PersistenceException = " + e - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + + "\n SUCCESS! Transaction Wait Timeout worked!" + "\n Caught PersistenceException = " + e + + "\n TimeStamp = " + date.getTime() + "\n\n"); } } catch (Exception e) { // failure due to some other reason - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE" - + "\n Caught Exception = " + e - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE" + "\n Caught Exception = " + e + + "\n TimeStamp = " + date.getTime() + "\n\n"); } - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); Assert.fail(); } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nthreadingStabilityTest() exit" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); + if (logger.isDebugEnabled()) { + Date date = new java.util.Date(); + logger.debug("\n\nthreadingStabilityTest() exit" + "\n TimeStamp = " + date.getTime() + "\n\n"); } } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java index dbddecc51..007d02120 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. * 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,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; - +import com.att.research.xacml.api.pap.PAPException; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; @@ -31,32 +32,32 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import javax.servlet.ReadListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; 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.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyVersion; import org.springframework.mock.web.MockServletConfig; -import com.att.research.xacml.api.pap.PAPException; - public class PushPolicyControllerTest { private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class); private static CommonClassDao commonClassDao; + private static SessionFactory sessionFactory; private String jsonString = null; private HttpServletRequest request = null; private PushPolicyController controller = null; @@ -65,6 +66,11 @@ public class PushPolicyControllerTest { private ServletConfig servletConfig; private XACMLPapServlet pap; + @BeforeClass + public static void beforeClassSetup() throws ServletException { + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest"); + } + @Before public void setUp() throws Exception { logger.info("setUp: Entering"); @@ -77,7 +83,7 @@ public class PushPolicyControllerTest { System.setProperty("com.sun.management.jmxremote.port", "9993"); Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("src/test/resources/xacml.pap.properties"); - + commonClassDao = Mockito.mock(CommonClassDao.class); controller = new PushPolicyController(); controller.setCommonClassDao(commonClassDao); @@ -118,10 +124,11 @@ public class PushPolicyControllerTest { } public ServletInputStream getInputStream(byte[] body) throws IOException { - final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); - ServletInputStream servletInputStream = new ServletInputStream() { - public int read() throws IOException { - return byteArrayInputStream.read(); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); + ServletInputStream servletInputStream = new ServletInputStream() { + @Override + public int read() throws IOException { + return byteArrayInputStream.read(); } @Override @@ -137,9 +144,9 @@ public class PushPolicyControllerTest { @Override public void setReadListener(ReadListener readListener) { } - }; - return servletInputStream; - } + }; + return servletInputStream; + } @After public void destroy(){ diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java index 84f36aa63..e7ab36e7a 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. * 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. @@ -24,13 +24,22 @@ 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.when; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; +import java.util.Collections; +import java.util.List; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.policy.common.logging.ONAPLoggingContext; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; @@ -38,15 +47,20 @@ import org.onap.policy.xacml.std.pap.StdEngine; import org.powermock.api.mockito.PowerMockito; 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; -import java.sql.Connection; -import java.util.Collections; -import java.util.List; -import javax.persistence.EntityManager; @RunWith(PowerMockRunner.class) public class DeleteHandlerTest { + @Before + public void setUp() { + SessionFactory mockedSessionFactory = Mockito.mock(SessionFactory.class); + Session mockedSession = Mockito.mock(Session.class); + Transaction mockedTransaction = Mockito.mock(Transaction.class); + Mockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession); + Mockito.when(mockedSession.beginTransaction()).thenReturn(mockedTransaction); + CommonClassDaoImpl.setSessionfactory(mockedSessionFactory); + new DeleteHandler(new CommonClassDaoImpl()); + } + @Test public void testGets() { DeleteHandler handler = new DeleteHandler(); @@ -79,17 +93,13 @@ public class DeleteHandlerTest { PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class); PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller); - // Mock entity manager - EntityManager em = Mockito.mock(EntityManager.class); - - // Test deletion from PAP - MockHttpServletResponse response = new MockHttpServletResponse(); - try { - handler.doAPIDeleteFromPAP(request, response); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } + // Test deletion from PAP + MockHttpServletResponse response = new MockHttpServletResponse(); + try { + handler.doAPIDeleteFromPAP(request, response); + } catch (Exception ex) { + fail("Not expecting an exception: " + ex); + } // Test deletion from PDP ONAPLoggingContext loggingContext = Mockito.mock(ONAPLoggingContext.class); @@ -100,15 +110,14 @@ public class DeleteHandlerTest { fail("Not expecting an exception: " + ex); } - // Test delete entity - PolicyEntity policyEntity = new PolicyEntity(); - policyEntity.setPolicyName("testVal"); - String result = DeleteHandler.deletePolicyEntityData(em, policyEntity); - assertEquals(result, "success"); + // Test delete entity + PolicyEntity policyEntity = new PolicyEntity(); + policyEntity.setPolicyName("testVal"); + String result = DeleteHandler.deletePolicyEntityData(policyEntity); + assertEquals(result, "success"); - // Test check entity - Connection con = null; - List<?> peResult = Collections.emptyList(); - assertEquals(DeleteHandler.checkPolicyGroupEntity(con, peResult), false); - } + // Test check entity + List<?> peResult = Collections.emptyList(); + assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java index 6971ed706..3daed2455 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,54 +22,63 @@ package org.onap.policy.pap.xacml.rest.handler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import com.mockrunner.mock.web.MockHttpServletResponse; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import javax.script.SimpleBindings; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPPolicy; -import org.powermock.api.mockito.PowerMockito; -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; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.servlet.http.HttpServletResponse; -import javax.persistence.Query; -@RunWith(PowerMockRunner.class) + public class PushPolicyHandlerTest { - @PrepareForTest({XACMLPapServlet.class}) @Test public void testGetsAndChecks() { - // Mock servlet, entity mgr, transaction, and query - EntityManager em = Mockito.mock(EntityManager.class); - EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); - PowerMockito.mockStatic(XACMLPapServlet.class); - PowerMockito.when(XACMLPapServlet.getEmf()).thenReturn(emf); - Mockito.when(emf.createEntityManager()).thenReturn(em); - EntityTransaction transaction = Mockito.mock(EntityTransaction.class); - Mockito.when(em.getTransaction()).thenReturn(transaction); - Query query = Mockito.mock(Query.class); - Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query); - + CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class); // Test constructor - PushPolicyHandler handler = new PushPolicyHandler(); + PushPolicyHandler handler = new PushPolicyHandler(commonClassDao); assertNotNull(handler); // Test gets - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(MockHttpServletResponse.class); + Mockito.when(request.getParameter("policyScope")).thenReturn("com"); + Mockito.when(request.getParameter("filePrefix")).thenReturn("Config_"); + Mockito.when(request.getParameter("policyName")).thenReturn("testPush"); + PolicyVersion version = new PolicyVersion(); + version.setActiveVersion(1); + version.setCreatedBy("API"); + version.setHigherVersion(1); + version.setId(1); + version.setModifiedBy("API"); + version.setPolicyName("com" + File.separator + "Config_testPush"); + List<PolicyVersion> list = new ArrayList<>(); + list.add(version); + + doNothing().when(commonClassDao).save(any(PolicyVersion.class)); + doReturn(list).when(commonClassDao).getDataByQuery(any(String.class), any(SimpleBindings.class)); + handler.getActiveVersion(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - request.setupAddParameter("gitPath", "testPath"); + + Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); + Mockito.verify(response).addHeader("version", "1"); + + request = Mockito.mock(HttpServletRequest.class); + response = Mockito.mock(MockHttpServletResponse.class); + Mockito.when(request.getParameter("gitPath")).thenReturn("testPath"); handler.getSelectedURI(request, response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); - // Test check StdPDPPolicy policy = new StdPDPPolicy(); OnapPDPGroup onapPolicy = new StdPDPGroup(); String configHome = "testVal"; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java index 81b5927c1..ad8f86c59 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java @@ -2,16 +2,16 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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 * ================================================================================ * 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. @@ -24,24 +24,23 @@ package org.onap.policy.pap.xacml.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Query; +import org.junit.BeforeClass; import org.junit.Test; -import org.mockito.Mockito; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; public class JPAUtilsTest { + @BeforeClass + public static void beforeClassSetup() { + PolicyDBDaoTest.setupH2DbDaoImpl("jpautilstest"); + new JPAUtils(new CommonClassDaoImpl()); + } + @Test(expected = IllegalAccessException.class) - public void testJPAUtils() throws IllegalAccessException { - // Setup test data - EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); - EntityManager em = Mockito.mock(EntityManager.class); - Query query = Mockito.mock(Query.class); - Mockito.when(emf.createEntityManager()).thenReturn(em); - Mockito.when(em.createNamedQuery(Mockito.any())).thenReturn(query); + public void testJpaUtils() throws IllegalAccessException { // Test lockdown - JPAUtils utils = JPAUtils.getJPAUtilsInstance(emf); + JPAUtils utils = JPAUtils.getJPAUtilsInstance(); assertEquals(utils.dbLockdownIgnoreErrors(), false); utils.dbLockdown(); fail("Expecting an exception"); |