diff options
Diffstat (limited to 'ONAP-PAP-REST/src/test/java/org/onap/policy')
56 files changed, 2754 insertions, 1603 deletions
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java index 9fded580c..b6b674dc7 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java @@ -86,7 +86,7 @@ public class DbAuditCompareEntriesTest { persistenceUnit = "testPapPU"; resourceName = "siteA.pap1"; - //Clean the iaTest DB table for IntegrityAuditEntity entries + // Clean the iaTest DB table for IntegrityAuditEntity entries cleanDb(persistenceUnit, properties); logger.info("setUp: Exiting"); @@ -95,11 +95,11 @@ public class DbAuditCompareEntriesTest { @After public void tearDown() throws Exception { logger.info("tearDown: Entering"); - //nothing to do + // nothing to do logger.info("tearDown: Exiting"); } - public void cleanDb(String persistenceUnit, Properties properties){ + public void cleanDb(String persistenceUnit, Properties properties) { logger.debug("cleanDb: enter"); EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); @@ -119,7 +119,6 @@ public class DbAuditCompareEntriesTest { logger.debug("cleanDb: exit"); } - /* * Tests that a comparison between hashsets is successful if * the entries match @@ -128,20 +127,18 @@ public class DbAuditCompareEntriesTest { public void runAllTests() throws Exception { logger.info("runAllTests: Entering"); - testIntegrityAuditEntity(); testBackupMonitorEntity(); testStateManagementEntity(); testForwardProgressEntity(); testResourceRegistrationEntity(); - //clean up the IntegrityAuditEntity table + // clean up the IntegrityAuditEntity table cleanDb(persistenceUnit, properties); logger.info("runAllTests: Exit"); } - public void testIntegrityAuditEntity() throws Exception { logger.info("testIntegrityAuditEntity: Entering"); @@ -149,10 +146,10 @@ public class DbAuditCompareEntriesTest { DbAudit dbAudit = new DbAudit(dbDAO); String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway + // There is only one entry IntegrityAuditEntity, but we will check anyway Set<String> classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){ + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { className = c; } } @@ -231,7 +228,6 @@ public class DbAuditCompareEntriesTest { // Two entries with the same field values - entry1.setFlag("flag1"); entry1.setResourceNodeName("node1"); entry1.setResourceName("resourceName"); @@ -248,17 +244,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ - - + ************************************/ // Change a field on entry2 @@ -272,8 +265,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testBackupMonitorEntity: Exit"); @@ -308,17 +300,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ - - + ************************************/ // Change a field on entry2 @@ -332,8 +321,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testStateManagementEntity: Exit"); @@ -365,15 +353,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ + ************************************/ // Change a field on entry2 @@ -387,8 +374,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testForwardProgressEntity: Exit"); @@ -422,15 +408,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ + ************************************/ // Change a field on entry2 @@ -444,10 +429,9 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testResourceRegistrationEntity: Exit"); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java index 5a8e20b26..fcec4a652 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.anyString; import java.io.File; import java.util.ArrayList; @@ -34,7 +36,6 @@ import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Matchers; import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -42,13 +43,16 @@ import org.onap.policy.pap.xacml.rest.UpdateOthersPAPS; import org.onap.policy.pap.xacml.rest.adapters.UpdateObjectData; import org.onap.policy.pap.xacml.rest.components.Policy; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xalan.*", "com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) +@PrepareForTest(UpdateOthersPAPS.class) public class UpdateOthersPAPSTest { private static Logger logger = FlexLogger.getLogger(UpdateOthersPAPSTest.class); @@ -60,28 +64,28 @@ public class UpdateOthersPAPSTest { public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); - - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); List<Object> data = new ArrayList<>(); - PolicyDBDaoEntity entity = new PolicyDBDaoEntity(); - entity.setPolicyDBDaoUrl("http://localhost:8070/pap"); + PolicyDbDaoEntity entity = new PolicyDbDaoEntity(); + entity.setPolicyDbDaoUrl("http://localhost:8070/pap"); entity.setUsername("test"); entity.setPassword("test"); - PolicyDBDaoEntity entity1 = new PolicyDBDaoEntity(); - entity1.setPolicyDBDaoUrl("http://localhost:8071/pap"); + PolicyDbDaoEntity entity1 = new PolicyDbDaoEntity(); + entity1.setPolicyDbDaoUrl("http://localhost:8071/pap"); entity1.setUsername("test"); entity1.setPassword("test"); data.add(entity); data.add(entity1); - System.setProperty("xacml.rest.pap.url","http://localhost:8070/pap"); - when(commonClassDao.getData(PolicyDBDaoEntity.class)).thenReturn(data); + System.setProperty("xacml.rest.pap.url", "http://localhost:8070/pap"); + when(commonClassDao.getData(PolicyDbDaoEntity.class)).thenReturn(data); } @Test - public void testNotifyOthersPAPsToUpdateConfigurations(){ + public void testNotifyOthersPAPsToUpdateConfigurations() { UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS(); UpdateOthersPAPS.setCommonClassDao(commonClassDao); when(request.getParameter("action")).thenReturn("rename"); @@ -98,7 +102,7 @@ public class UpdateOthersPAPSTest { @PrepareForTest({Policy.class}) @Test - public void testUpdateConfiguration() throws Exception{ + public void testUpdateConfiguration() throws Exception { UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS(); UpdateObjectData data = new UpdateObjectData(); PowerMockito.mockStatic(Policy.class); @@ -109,7 +113,8 @@ public class UpdateOthersPAPSTest { when(Policy.getActionHome()).thenReturn("test"); File mockedFile = Mockito.mock(File.class); Mockito.when(mockedFile.exists()).thenReturn(true); - PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile); + PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(anyString()) + .thenReturn(mockedFile); updateOtherPaps.updateConfiguration(data, response); assertTrue(response.getStatus() == 200); } 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 fd0c157fe..f9faa2928 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 @@ -24,7 +24,9 @@ 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; @@ -36,11 +38,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; + 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; @@ -67,7 +71,7 @@ import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionPolicyDict; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.Category; import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.rest.jpa.PolicyEditorScopes; @@ -79,7 +83,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletConfig; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; - public class XACMLPAPTest { private static final Log logger = LogFactory.getLog(XACMLPAPTest.class); @@ -93,10 +96,6 @@ public class XACMLPAPTest { 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 = ""; - @BeforeClass public static void beforeClassSetup() throws ServletException { sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("xacmlpaptest"); @@ -336,7 +335,6 @@ public class XACMLPAPTest { Mockito.verify(httpServletResponse).addHeader("operation", "create"); } - @Test public void testDecisonBLGuardPolicy() throws IOException, ServletException, SQLException { httpServletRequest = Mockito.mock(HttpServletRequest.class); @@ -449,7 +447,6 @@ public class XACMLPAPTest { Mockito.verify(httpServletResponse).addHeader("operation", "create"); } - private void setPolicyCreation() { CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class); PolicyCreation.setCommonClassDao(commonClassDao); @@ -462,7 +459,7 @@ public class XACMLPAPTest { editorScope.setUserModifiedBy(userInfo); Mockito.when(commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", "test")) .thenReturn(editorScope); - BRMSParamTemplate template = new BRMSParamTemplate(); + 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" @@ -474,7 +471,7 @@ public class XACMLPAPTest { + "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")) + Mockito.when(commonClassDao.getEntityItem(BrmsParamTemplate.class, "ruleName", "testPolicy")) .thenReturn(template); } @@ -491,7 +488,7 @@ public class XACMLPAPTest { // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check VNFType + // Check VnfType // httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); @@ -502,14 +499,14 @@ public class XACMLPAPTest { // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); // - // Check PEPOptions + // 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\"}]}}"; - dictionaryTestSetup(false, "PEPOptions", json); + dictionaryTestSetup(false, "PepOptions", json); // send Request to PAP pap.service(httpServletRequest, httpServletResponse); // Verify @@ -698,7 +695,6 @@ public class XACMLPAPTest { // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl" @@ -890,7 +886,7 @@ 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", + "VNFType", "PepOptions", "Varbind", "Service", "Site", "Settings", "RainyDayTreatments", "DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone", "PrefixList", "AddressGroup", "ServiceGroup", "ServiceList", "TermList", "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID", "MicroServiceModels", "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType", diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java index 49120a0d9..36e67a718 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +27,7 @@ import static org.mockito.Mockito.when; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -34,12 +36,16 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.IOUtils; import org.hibernate.SessionFactory; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -49,13 +55,13 @@ import org.mockito.Mockito; import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.pap.xacml.rest.components.ConfigPolicy; import org.onap.policy.pap.xacml.rest.components.Policy; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.xacml.std.pap.StdEngine; import org.onap.policy.xacml.std.pap.StdPDP; import org.springframework.mock.web.DelegatingServletInputStream; @@ -84,7 +90,7 @@ public class ConsoleAndApiServiceTest { private static final String APIFLAG = "apiflag"; private static final String ENVIRONMENT_HEADER = "Environment"; private static final OnapLoggingContext logContext = Mockito.mock(OnapLoggingContext.class); - private static PolicyDBDao dbd; + private static PolicyDbDao dbd; private static StdEngine stdEngine = null; private static SessionFactory sessionFactory = null; private static List<String> headers = new ArrayList<>(); @@ -105,9 +111,9 @@ public class ConsoleAndApiServiceTest { public static void setUpBeforeClass() throws Exception { System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testConsoleApi"); - PolicyDBDao.setJunit(true); - dbd = PolicyDBDao.getPolicyDBDaoInstance(); - PolicyDBDao.setJunit(true); + PolicyDbDao.setJunit(true); + dbd = PolicyDbDao.getPolicyDbDaoInstance(); + PolicyDbDao.setJunit(true); consoleAndApi = new ConsoleAndApiService(); servletConfig = Mockito.mock(MockServletConfig.class); @@ -119,6 +125,10 @@ public class ConsoleAndApiServiceTest { pap.init(servletConfig); } + @AfterClass + public static void after() { + pap.destroy(); + } /** * Sets the up. @@ -228,7 +238,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null); Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); Mockito.when(httpServletRequest.getMethod()).thenReturn(PUT); @@ -240,7 +249,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPut(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = new MockHttpServletResponse(); Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); @@ -252,7 +260,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = new MockHttpServletResponse(); Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); @@ -264,7 +271,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcDelete(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - } @Test @@ -293,7 +299,7 @@ public class ConsoleAndApiServiceTest { assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus()); } - private static void populatePolicyInDb() throws IOException, PolicyDBException { + private static void populatePolicyInDb() throws IOException, PolicyDbException { CommonClassDaoImpl.setSessionfactory(sessionFactory); PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); Policy policyObject = new ConfigPolicy(); @@ -318,7 +324,7 @@ public class ConsoleAndApiServiceTest { policyObject.policyAdapter.setParentPath(IOUtils.toString( ConsoleAndApiServiceTest.class.getClassLoader().getResourceAsStream("Config_SampleTest1206.1.xml"))); - PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + PolicyDbDaoTransaction transaction = dbd.getNewTransaction(); transaction.createPolicy(policyObject, API); transaction.commitTransaction(); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java new file mode 100644 index 000000000..33b7f8be6 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.att.research.xacml.api.pap.PAPException; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; + +public class HeartbeatTest { + @Test + public void testHeartbeat() throws IOException, PAPException { + Heartbeat hb = new Heartbeat(null); + + assertThatThrownBy(hb::run).isInstanceOf(NullPointerException.class); + assertTrue(hb.isHeartBeatRunning()); + hb.terminate(); + assertFalse(hb.isHeartBeatRunning()); + } + + @Test + public void testGetPdps() throws PAPException, IOException { + Set<OnapPDPGroup> pdpGroups = new HashSet<OnapPDPGroup>(); + StdPDPGroup pdpGroup = new StdPDPGroup(); + OnapPDP pdp = new StdPDP(); + pdpGroup.addPDP(pdp); + pdpGroups.add(pdpGroup); + PAPPolicyEngine pap = Mockito.mock(PAPPolicyEngine.class); + Mockito.when(pap.getOnapPDPGroups()).thenReturn(pdpGroups); + Heartbeat hb = new Heartbeat(pap); + hb.getPdpsFromGroup(); + assertFalse(hb.isHeartBeatRunning()); + + assertThatCode(hb::notifyEachPdp).doesNotThrowAnyException(); + assertThatThrownBy(hb::run).isInstanceOf(Exception.class); + assertThatThrownBy(hb::notifyEachPdp).isInstanceOf(Exception.class); + } + + @Test + public void testOpen() throws MalformedURLException { + Heartbeat hb = new Heartbeat(null); + OnapPDP pdp = new StdPDP(); + + assertThatCode(() -> { + URL url = new URL("http://onap.org"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + URL url = new URL("http://1.2.3.4"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + URL url = new URL("http://fakesite.fakenews"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java index dfadf8e81..2815328a8 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest; import static org.junit.Assert.assertEquals; + import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.junit.Test; @@ -45,7 +46,9 @@ public class PAPRestConfigTest { @Test public void testInit() { String driver = "org.mariadb.jdbc.Driver"; - String url = "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=true&sessionVariables=max_statement_time=30"; + String url = + "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=" + + "true&sessionVariables=max_statement_time=30"; String user = "policy_user"; String password = "policy_user"; @@ -58,7 +61,7 @@ public class PAPRestConfigTest { assertEquals(PAPRestConfig.getDbPassword(), password); // Test hibernate - BasicDataSource source = (BasicDataSource)config.getDataSource(); + BasicDataSource source = (BasicDataSource) config.getDataSource(); assertEquals(source.getDriverClassName(), driver); assertEquals(source.getUrl(), url); assertEquals(source.getUsername(), user); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java new file mode 100644 index 000000000..9034f393b --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.junit.Test; +import org.onap.policy.common.logging.OnapLoggingContext; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.std.pap.StdPDP; + +public class UpdatePdpThreadTest { + @Test + public void testConstructor1() { + UpdatePdpThread thread = new UpdatePdpThread(null, null); + assertNotNull(thread); + } + + @Test + public void testConstructor2() { + OnapLoggingContext loggingContext = new OnapLoggingContext(); + loggingContext.setRequestId("id"); + UpdatePdpThread thread = new UpdatePdpThread(null, loggingContext, null); + assertNotNull(thread); + } + + @Test + public void testRun() { + OnapPDP pdp = new StdPDP("http://id", 0); + OnapLoggingContext loggingContext = new OnapLoggingContext(); + loggingContext.setRequestId("id"); + List<Properties> properties = new ArrayList<Properties>(); + UpdatePdpThread thread = new UpdatePdpThread(pdp, loggingContext, properties); + assertThatCode(thread::run).doesNotThrowAnyException(); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java index 32d7dedd3..22f657249 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.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. @@ -21,13 +21,15 @@ package org.onap.policy.pap.xacml.rest; import static org.junit.Assert.fail; + import javax.servlet.ServletContext; import javax.servlet.ServletException; + import org.junit.Test; import org.mockito.Mockito; public class WebConfigTest { - @Test(expected=NullPointerException.class) + @Test(expected = NullPointerException.class) public void testNegativeStartup() throws ServletException { WebConfig init = new WebConfig(); ServletContext container = Mockito.mock(ServletContext.class); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java index 36d40278b..420e380b6 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.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. @@ -20,31 +20,46 @@ package org.onap.policy.pap.xacml.rest; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; +import java.io.IOException; +import java.util.Properties; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.onap.policy.pap.xacml.rest.XACMLPapServlet; public class XACMLPapServletTest { + String systemKey = "xacml.properties"; + String oldProperty = System.getProperty(systemKey); + + @Before + public void setup() { + // Set the system property temporarily + System.setProperty(systemKey, "xacml.pap.properties"); + } + @Test public void testSetAndGet() { - String systemKey = "xacml.properties"; String testVal = "testVal"; XACMLPapServlet servlet = new XACMLPapServlet(); - // Set the system property temporarily - String oldProperty = System.getProperty(systemKey); - System.setProperty(systemKey, "xacml.pap.properties"); - + assertNotNull(servlet); assertNotNull(XACMLPapServlet.getConfigHome()); assertNotNull(XACMLPapServlet.getActionHome()); assertEquals(XACMLPapServlet.getPersistenceUnit(), "XACML-PAP-REST"); - //assertNull(XACMLPapServlet.getEmf()); - //assertNull(XACMLPapServlet.getPDPFile()); - //assertNull(XACMLPapServlet.getPAPEngine()); - //assertNull(servlet.getIa()); - XACMLPapServlet.setPapDbDriver(testVal); assertEquals(XACMLPapServlet.getPapDbDriver(), testVal); XACMLPapServlet.setPapDbUrl(testVal); @@ -57,12 +72,38 @@ public class XACMLPapServletTest { assertEquals(XACMLPapServlet.getMsOnapName(), testVal); XACMLPapServlet.setMsPolicyName(testVal); assertEquals(XACMLPapServlet.getMsPolicyName(), testVal); + } + + @Test + public void testMethods() throws ServletException, IOException, PAPException { + XACMLPapServlet servlet = new XACMLPapServlet(); + + ObjectMapper mapper = new ObjectMapper(); + HttpServletResponse response = new MockHttpServletResponse(); + assertThatCode(() -> XACMLPapServlet.mapperWriteValue(mapper, response, "hello")).doesNotThrowAnyException(); + assertThatCode(() -> XACMLPapServlet.mapperWriteValue(null, null, null)).doesNotThrowAnyException(); + assertNull(XACMLPapServlet.getPapUrl()); + HttpServletRequest request = new MockHttpServletRequest(); + assertThatThrownBy(() -> servlet.doDelete(request, response)).isInstanceOf(NullPointerException.class); + + StringBuffer urlPath = new StringBuffer("http://foo"); + Properties policies = new Properties(); + servlet.populatePolicyURL(urlPath, policies); + assertNull(policies.getProperty("foo.url")); + + policies.setProperty(XACMLProperties.PROP_ROOTPOLICIES, "foo"); + policies.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "bar"); + servlet.populatePolicyURL(urlPath, policies); + assertEquals("http://foo?id=foo", policies.getProperty("foo.url")); + } + + @After + public void after() { // Restore the original system property if (oldProperty != null) { - System.setProperty(systemKey, oldProperty); - } - else { + System.setProperty(systemKey, oldProperty); + } else { System.clearProperty(systemKey); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java index 841ba28fc..1b1564cf9 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java @@ -2,7 +2,7 @@ * ============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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; import static org.junit.Assert.*; @@ -25,9 +26,8 @@ import org.junit.Test; public class SearchDataTest { - @Test - public void testSearchData(){ + public void testSearchData() { String data = "Test"; SearchData searchData = new SearchData(); searchData.setQuery(data); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java index 094994e41..00649c5e2 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; import static org.junit.Assert.assertTrue; @@ -26,7 +27,7 @@ import org.junit.Test; public class UpdateObjectDataTest { @Test - public void testClosedLoopFaultTrapDatas(){ + public void testClosedLoopFaultTrapDatas() { UpdateObjectData updateObject = new UpdateObjectData(); updateObject.setAction("Rename"); assertTrue("Rename".equals(updateObject.getAction())); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java index b80eaed89..6f4e09775 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.*; 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.After; import org.junit.Before; import org.junit.Test; @@ -35,8 +40,6 @@ import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import com.att.research.xacml.util.XACMLProperties; - public class ActionPolicyTest { @@ -55,8 +58,7 @@ public class ActionPolicyTest { @Before public void setUp() throws Exception { logger.info("setUp: Entering"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, - "src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); dynamicRuleAlgorithmLabels.add("test"); dynamicRuleAlgorithmField1.add("testField1"); @@ -65,8 +67,7 @@ public class ActionPolicyTest { policyAdapter.setPolicyName("Test.Action_junitTest"); policyAdapter.setPolicyDescription("test"); - policyAdapter.setRuleCombiningAlgId( - "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); policyAdapter.setPolicyType("Action"); policyAdapter.setEditPolicy(false); policyAdapter.setDomainDir("Test"); @@ -95,12 +96,6 @@ public class ActionPolicyTest { } /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** * Test method for * {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}. */ diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java index 39586ba1b..5c1d3dd76 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java @@ -2,7 +2,7 @@ * ============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 * ================================================================================ @@ -19,15 +19,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.att.research.xacml.api.pap.PAPException; import java.io.IOException; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; +import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; public class BRMSPolicyTest { @@ -65,4 +75,42 @@ public class BRMSPolicyTest { String userID = "testID"; assertEquals(1, template.addRule(rule, ruleName, description, userID).size()); } + + @Test + public void testCreateBrmsParamPolicyAdapter() throws PAPException { + Map<String, String> brmsParamBody = new HashMap<String, String>(); + brmsParamBody.put("key", "value"); + + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setHighestVersion(1); + adapter.setPolicyType("Config"); + adapter.setBrmsParamBody(brmsParamBody); + adapter.setNewFileName("policyName.1.xml"); + Map<String, String> dynamicFieldConfigAttributes = new HashMap<String, String>(); + dynamicFieldConfigAttributes.put("key", "value"); + adapter.setDynamicFieldConfigAttributes(dynamicFieldConfigAttributes); + CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(adapter); + String ruleContents = "contents"; + + assertThatCode(() -> policy.saveConfigurations("name.xml", "rules")).doesNotThrowAnyException(); + try { + policy.prepareToSave(); + policy.savePolicies(); + } catch (Exception ex) { + // Ignore + } + + assertThatThrownBy(() -> policy.expandConfigBody(ruleContents, brmsParamBody)) + .isInstanceOf(NullPointerException.class); + assertTrue(policy.validateConfigForm()); + policy.getAdviceExpressions(1, "name.1.xml"); + assertNotNull(policy.getCorrectPolicyDataObject()); + } + + @Test + public void testRead() { + Charset encoding = Charset.defaultCharset(); + assertThatCode(() -> CreateBrmsParamPolicy.readFile("xacml.pap.properties", encoding)) + .doesNotThrowAnyException(); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java index 542d45e3e..75fa23605 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.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,19 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; -import java.io.IOException; -import org.onap.policy.rest.adapter.PolicyRestAdapter; + import com.att.research.xacml.api.pap.PAPException; + +import java.io.IOException; import java.nio.charset.StandardCharsets; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class ClosedLoopPolicyTest { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -51,7 +55,7 @@ public class ClosedLoopPolicyTest { @Test public void testReadFile() throws IOException { thrown.expect(IOException.class); - String read = ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8); + ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8); fail("Expecting an exception."); } @@ -65,4 +69,4 @@ public class ClosedLoopPolicyTest { policy.prepareToSave(); assertEquals(policy.isPreparedToSave(), true); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java new file mode 100644 index 000000000..1e82bbd06 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.Collections; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; + +public class CreateNewMicroServiceModelTest { + @Test + public void testEmptyModel() { + CreateNewMicroServiceModel model = + new CreateNewMicroServiceModel("file.yml", "model", "desc", "1.0", "id"); + assertNotNull(model); + assertEquals(1, model.addValuesToNewModel(".yml").size()); + } + + @Test + public void testCreateConstructor1() { + CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null); + assertNotNull(model); + } + + @Test + public void testCreateModel() throws Exception { + // Mock file retrieval + File testFile = new File("testFile"); + File[] testList = new File[1]; + testList[0] = testFile; + File impl = Mockito.mock(File.class); + when(impl.listFiles()).thenReturn(testList); + when(impl.isFile()).thenReturn(true); + + // Mock internal dictionary retrieval + CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class); + when(daoImpl.getDataById(any(), anyString(), anyString())) + .thenReturn(Collections.emptyList()); + + // Test create methods + String testFileName = "testFile.yml"; + String testVal = "testVal"; + CreateNewMicroServiceModel model = + new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal); + assertEquals(1, model.addValuesToNewModel(".yml").size()); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java new file mode 100644 index 000000000..e6b9f47ca --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class CreateNewOptimizationTest { + @Test + public void testEmptyModel() { + CreateNewOptimizationModel model = new CreateNewOptimizationModel(); + assertNotNull(model); + model = new CreateNewOptimizationModel("file.yml", "model", "desc", "1.0", "id"); + assertNotNull(model); + assertEquals(1, model.addValuesToNewModel().size()); + } +} 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 ec9229c71..900d1227f 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 @@ -23,12 +23,15 @@ 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; @@ -61,7 +64,7 @@ public class DecisionPolicyTest { @Before public void setUp() throws Exception { logger.info("setUp: Entering"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); policyAdapter.setPolicyName("Test.Decision_junitTest.1.xml"); policyAdapter.setPolicyDescription("testing"); @@ -71,10 +74,10 @@ public class DecisionPolicyTest { policyAdapter.setDomainDir("Test"); policyAdapter.setNewFileName("/src/test/resources/Test/client.properties"); policyAdapter.setHighestVersion(1); - policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID()); + policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID()); policyAdapter.setOnapName("MSO"); - //rainy day attributes + // rainy day attributes attributeMap.put("ServiceType", "S"); attributeMap.put("VNFType", "V"); attributeMap.put("BB_ID", "testBB"); @@ -119,7 +122,7 @@ public class DecisionPolicyTest { e.printStackTrace(); } - assertEquals(successMap.get("success"),"success"); + assertEquals(successMap.get("success"), "success"); } /** @@ -135,7 +138,7 @@ public class DecisionPolicyTest { try { response = component.prepareToSave(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } assertTrue(response); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java index 7f3ebb3b4..4ddc8d057 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 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,15 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.*; import static org.mockito.Mockito.when; +import com.att.research.xacml.util.XACMLProperties; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; - import java.util.Map; import java.util.UUID; @@ -38,9 +40,6 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.test.XACMLPAPTest; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import com.att.research.xacml.util.XACMLProperties; - - public class FirewallConfigPolicyTest { private static Logger logger = FlexLogger.getLogger(FirewallConfigPolicyTest.class); @@ -56,7 +55,7 @@ public class FirewallConfigPolicyTest { @Before public void setUp() throws Exception { logger.info("setup: enter"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); policyAdapter.setPolicyName("FWjunitTest"); policyAdapter.setPolicyDescription("test"); @@ -68,7 +67,7 @@ public class FirewallConfigPolicyTest { policyAdapter.setNewFileName("Test.Config_FW_junitTest.1.xml"); policyAdapter.setHighestVersion(1); policyAdapter.setVersion(String.valueOf(1)); - policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID()); + policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID()); policyAdapter.setRuleID(""); policyAdapter.setConfigName("testname"); policyAdapter.setGuard("True"); @@ -106,7 +105,7 @@ public class FirewallConfigPolicyTest { when(mockFWConfig.savePolicies()).thenReturn(successMap); successMap = mockFWConfig.savePolicies(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } } @@ -122,29 +121,74 @@ public class FirewallConfigPolicyTest { when(mockFWConfig.prepareToSave()).thenReturn(true); response = mockFWConfig.prepareToSave(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } assertTrue(response); } @Test - public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy(); - Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class , String.class); + Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class, + String.class); method.setAccessible(true); - String jsonBody= "{\"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 prevJsonBody = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\",\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\",\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\",\"enabled\":true,\"log\":true}]}"; + String jsonBody = + "{\"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 prevJsonBody = + "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\"," + + "\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\"," + + "\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\"," + + "\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":" + + "\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\"," + + "\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":" + + "\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":" + + "\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":" + + "\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":" + + "\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":" + + "[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":" + + "[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\"," + + "\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":" + + "\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\"," + + "\"enabled\":true,\"log\":true}]}"; assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody)); } @Test - public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy(); Method method = firewallConfigPolicy.getClass().getDeclaredMethod("insertFirewallDicionaryData", String.class); method.setAccessible(true); - String jsonBody= "{\"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 jsonBody = + "{\"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}]}"; assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody)); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java index 436ff7fc8..86a7af11f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +23,13 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.IOException; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.IOUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -35,7 +39,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.xacml.std.pap.StdEngine; @@ -46,7 +50,7 @@ public class HandleIncomingNotificationsTest { private static final String PDP = "pdp"; private static final String GROUP = "group"; private static final String ONE = "1"; - private static PolicyDBDao dbd; + private static PolicyDbDao dbd; private static StdEngine stdEngine = null; private static SessionFactory sessionFactory = null; private static HandleIncomingNotifications handleIncomingNotifications; @@ -64,9 +68,9 @@ public class HandleIncomingNotificationsTest { System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testHandleIncoming"); handleIncomingNotifications = new HandleIncomingNotifications(sessionFactory); - PolicyDBDao.setJunit(true); - dbd = PolicyDBDao.getPolicyDBDaoInstance(); - PolicyDBDao.setJunit(true); + PolicyDbDao.setJunit(true); + dbd = PolicyDbDao.getPolicyDbDaoInstance(); + PolicyDbDao.setJunit(true); populateDb(); } @@ -93,7 +97,7 @@ public class HandleIncomingNotificationsTest { handleIncomingNotifications.handleIncomingHttpNotification(null, TWO, PDP, null, null); } - private static void populateDb() throws PolicyDBException, IOException { + private static void populateDb() throws PolicyDbException, IOException { groupEntity = new GroupEntity(); groupEntity.setCreatedBy(API); groupEntity.setDefaultGroup(false); @@ -130,7 +134,7 @@ public class HandleIncomingNotificationsTest { session.close(); } - private static void populatePolicyInDb() throws PolicyDBException, IOException { + private static void populatePolicyInDb() throws PolicyDbException, IOException { Policy policyObject = new ConfigPolicy(); policyObject.policyAdapter = new PolicyRestAdapter(); policyObject.policyAdapter.setConfigName("testpolicyhandle"); @@ -154,7 +158,7 @@ public class HandleIncomingNotificationsTest { policyObject.policyAdapter .setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"))); - PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + PolicyDbDaoTransaction transaction = dbd.getNewTransaction(); transaction.createPolicy(policyObject, "testuser1"); transaction.commitTransaction(); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java index f698bc0c0..35c99f770 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.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,29 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; +import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.Matchers.anyString; -import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; + +import com.att.research.xacml.api.pap.PAPException; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.util.Collections; -@RunWith(PowerMockRunner.class) public class MicroServicePolicyTest { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -59,53 +52,38 @@ public class MicroServicePolicyTest { assertNull(policy.getCorrectPolicyDataObject()); } - @PrepareForTest({MicroServiceConfigPolicy.class}) - @Test - public void testPrepareToSave() throws Exception { - // Need to mock internal dictionary retrieval - CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class); - PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl); - when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null); - + @Test(expected = NullPointerException.class) + public void testSave() throws PAPException { PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter); + PolicyType policyType = new PolicyType(); + policyAdapter.setPolicyID("id"); policyAdapter.setHighestVersion(1); policyAdapter.setPolicyType("Config"); - policyAdapter.setNewFileName("foo.xml"); - policyAdapter.setJsonBody("{ \"version\": \"1.0\"}"); - policyAdapter.setServiceType("foo"); - policy.prepareToSave(); - assertEquals(policy.isPreparedToSave(), true); - } + policyAdapter.setNewFileName("newfile"); + policyAdapter.setData(policyType); + policyAdapter.setJsonBody("{\"key\":\"value\"}"); + policyAdapter.setServiceType("svcType"); + MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter); - @Test - public void testCreateConstructor1() { - CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null); - assertNotNull(model); + policy.savePolicies(); } - @PrepareForTest({CreateNewMicroServiceModel.class}) @Test - public void testCreateModel() throws Exception { - // Mock file retrieval - File testFile = new File("testFile"); - File[] testList = new File[1]; - testList[0] = testFile; - File impl = Mockito.mock(File.class); - PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl); - when(impl.listFiles()).thenReturn(testList); - when(impl.isFile()).thenReturn(true); + public void testAdvice() { + PolicyType policyType = new PolicyType(); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setPolicyID("id"); + policyAdapter.setHighestVersion(1); + policyAdapter.setPolicyType("Config"); + policyAdapter.setNewFileName("newfile"); + policyAdapter.setData(policyType); + policyAdapter.setJsonBody("{\"key\":\"value\"}"); + policyAdapter.setServiceType("svcType"); - // Mock internal dictionary retrieval - CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class); - PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl); - when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList()); + MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter); + assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(NullPointerException.class); - // Test create methods - String testFileName = "testFile.zip"; - String testVal = "testVal"; - CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal); - model.addValuesToNewModel(".xmi"); - model.saveImportService(); + AdviceExpressionsType expType = policy.getAdviceExpressions(1, "filename"); + assertEquals(1, expType.getAdviceExpression().size()); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java new file mode 100644 index 000000000..7156ec788 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.att.research.xacml.util.XACMLProperties; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; + +public class NotifyOtherPapsTest { + private static final String systemKey = XACMLProperties.XACML_PROPERTIES_NAME; + private static final String oldProperty = System.getProperty(systemKey); + + @Before + public void setup() { + // Set the system property temporarily + System.setProperty(systemKey, "xacml.pap.properties"); + } + + @Test + public void negTestNotify() { + NotifyOtherPaps notify = new NotifyOtherPaps(); + List<PolicyDbDaoEntity> otherServers = new ArrayList<PolicyDbDaoEntity>(); + PolicyDbDaoEntity dbdaoEntity = new PolicyDbDaoEntity(); + dbdaoEntity.setPolicyDbDaoUrl("http://test"); + otherServers.add(dbdaoEntity); + long entityId = 0; + String entityType = "entityType"; + String newGroupId = "newGroupId"; + assertThatCode(() -> notify.startNotifyThreads(otherServers, entityId, entityType, newGroupId)) + .doesNotThrowAnyException(); + } + + @After + public void cleanup() { + // Restore the original system property + if (oldProperty != null) { + System.setProperty(systemKey, oldProperty); + } else { + System.clearProperty(systemKey); + } + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java index 25e94c1a2..8437fb0f7 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.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,29 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; +import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.Matchers.anyString; -import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; + +import com.att.research.xacml.api.pap.PAPException; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.util.Collections; -@RunWith(PowerMockRunner.class) public class OptimizationConfigPolicyTest { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -59,47 +52,37 @@ public class OptimizationConfigPolicyTest { assertNull(policy.getCorrectPolicyDataObject()); } - @PrepareForTest({OptimizationConfigPolicy.class}) @Test - public void testPrepareToSave() throws Exception { - // Need to mock internal dictionary retrieval - CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class); - PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl); - when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null); - + public void testSave() throws PAPException { + PolicyType policyType = new PolicyType(); PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter); + policyAdapter.setPolicyID("id"); policyAdapter.setHighestVersion(1); policyAdapter.setPolicyType("Config"); - policyAdapter.setNewFileName("foo.xml"); - policyAdapter.setJsonBody("{ \"version\": \"1.0\"}"); - policyAdapter.setServiceType("foo"); - policy.prepareToSave(); - assertEquals(true, policy.isPreparedToSave()); + policyAdapter.setNewFileName("newfile"); + policyAdapter.setData(policyType); + policyAdapter.setJsonBody("{\"key\":\"value\"}"); + policyAdapter.setServiceType("svcType"); + OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter); + assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(Exception.class); } - @PrepareForTest({CreateNewOptimizationModel.class}) @Test - public void testCreateModel() throws Exception { - // Mock file retrieval - File testFile = new File("testFile"); - File[] testList = new File[1]; - testList[0] = testFile; - File impl = Mockito.mock(File.class); - PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl); - when(impl.listFiles()).thenReturn(testList); - when(impl.isFile()).thenReturn(true); + public void testAdvice() { + PolicyType policyType = new PolicyType(); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setPolicyID("id"); + policyAdapter.setHighestVersion(1); + policyAdapter.setPolicyType("Config"); + policyAdapter.setNewFileName("newfile"); + policyAdapter.setData(policyType); + policyAdapter.setJsonBody("{\"key\":\"value\"}"); + policyAdapter.setServiceType("svcType"); - // Mock internal dictionary retrieval - CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class); - PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl); - when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList()); + OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter); + assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(Exception.class); - // Test create methods - String testFileName = "testFile.zip"; - String testVal = "testVal"; - CreateNewOptimizationModel model = new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal); - model.addValuesToNewModel(); - model.saveImportService(); + AdviceExpressionsType expType = policy.getAdviceExpressions(1, "filename"); + assertEquals(1, expType.getAdviceExpression().size()); } } 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 e4da430a5..99cc47c23 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 @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +22,10 @@ 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; @@ -30,12 +33,12 @@ import java.nio.file.Paths; import java.util.Date; import java.util.List; import java.util.Properties; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceException; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; @@ -50,12 +53,12 @@ import org.junit.Test; 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.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.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +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; @@ -69,9 +72,9 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; public class PolicyDBDaoTest { private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class); - static PolicyDBDaoTestClass d; - static PolicyDBDao dbd; - static PolicyDBDao dbd2; + static PolicyDbDaoTestClass d; + static PolicyDbDao dbd; + static PolicyDbDao dbd2; private static Path repository; static StdEngine stdEngine = null; static SessionFactory sessionFactory = null; @@ -81,14 +84,14 @@ public class PolicyDBDaoTest { System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); try { sessionFactory = setupH2DbDaoImpl("testdbdao"); - dbd = PolicyDBDao.getPolicyDBDaoInstance(); - dbd2 = PolicyDBDao.getPolicyDBDaoInstance(); + dbd = PolicyDbDao.getPolicyDbDaoInstance(); + dbd2 = PolicyDbDao.getPolicyDbDaoInstance(); } catch (Exception e) { Assert.fail(); } - d = PolicyDBDao.getPolicyDBDaoTestClass(); - PolicyDBDao.setJunit(true); + d = PolicyDbDao.getPolicyDbDaoTestClass(); + PolicyDbDao.setJunit(true); repository = Paths.get("src/test/resources/pdps"); stdEngine = new StdEngine(repository); dbd.setPapEngine(stdEngine); @@ -123,7 +126,7 @@ public class PolicyDBDaoTest { sessionBuilder.addProperties(properties); SessionFactory sessionFac = sessionBuilder.buildSessionFactory(); - new PolicyDBDao(sessionFac); + new PolicyDbDao(sessionFac); PolicyDbDaoTransactionInstance.setJunit(true); new PolicyDbDaoTransactionInstance(sessionFac); CommonClassDaoImpl.setSessionfactory(sessionFac); @@ -156,13 +159,12 @@ public class PolicyDBDaoTest { return sessionFac; } - private static void setUpAuditDb() { Properties properties = new Properties(); - properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); - properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); - properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); - properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); + properties.put(XacmlRestProperties.PROP_PAP_DB_DRIVER, "org.h2.Driver"); + properties.put(XacmlRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); + properties.put(XacmlRestProperties.PROP_PAP_DB_USER, "sa"); + properties.put(XacmlRestProperties.PROP_PAP_DB_PASSWORD, ""); // create the DB and then close it Persistence.createEntityManagerFactory("testPapPU", properties).close(); @@ -180,7 +182,7 @@ public class PolicyDBDaoTest { } @Test - public void getPolicyNameAndVersionFromPolicyFileNameTest() throws PolicyDBException { + public void getPolicyNameAndVersionFromPolicyFileNameTest() throws PolicyDbException { String policyName = "com.Decision_testname.1.xml"; String[] expectedNameAndVersion = new String[2]; expectedNameAndVersion[0] = "com.Decision_testname"; @@ -249,7 +251,7 @@ public class PolicyDBDaoTest { fail(); } - PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + PolicyDbDaoTransaction transaction = dbd.getNewTransaction(); try { transaction.createPolicy(policyObject, "testuser1"); transaction.commitTransaction(); @@ -291,10 +293,10 @@ public class PolicyDBDaoTest { @Test public void groupTransactions() { - PolicyDBDaoTransaction group = dbd.getNewTransaction(); + PolicyDbDaoTransaction group = dbd.getNewTransaction(); String groupName = "test group 1"; try { - group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group", + group.createGroup(PolicyDbDao.createNewPdpGroupId(groupName), groupName, "this is a test group", "testuser"); group.commitTransaction(); } catch (Exception e) { @@ -306,18 +308,18 @@ public class PolicyDBDaoTest { 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("groupId", PolicyDbDao.createNewPdpGroupId(groupName)); getGroup.setParameter("deleted", false); List<?> groups = getGroup.list(); GroupEntity groupEntity = (GroupEntity) groups.get(0); - Assert.assertEquals(groupName, groupEntity.getgroupName()); + 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("/")); + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDbDao.createNewPdpGroupId(groupName), Paths.get("/")); group.deleteGroup(groupToDelete, null, "testuser"); group.commitTransaction(); } catch (Exception e) { @@ -329,7 +331,7 @@ public class PolicyDBDaoTest { 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("groupId", PolicyDbDao.createNewPdpGroupId(groupName)); getGroup2.setParameter("deleted", false); List<?> groups2 = getGroup2.list(); groups2 = getGroup2.list(); @@ -340,11 +342,10 @@ public class PolicyDBDaoTest { session2.getTransaction().commit(); session2.close(); - // add a pdp to a group group = dbd.getNewTransaction(); try { - group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser"); + group.createGroup(PolicyDbDao.createNewPdpGroupId(groupName), groupName, "test group", "testuser"); group.commitTransaction(); } catch (Exception e) { group.rollbackTransaction(); @@ -354,7 +355,7 @@ public class PolicyDBDaoTest { group = dbd.getNewTransaction(); try { - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDbDao.createNewPdpGroupId(groupName), "primary", "the main pdp", 3232, "testuser"); group.commitTransaction(); } catch (Exception e) { @@ -374,12 +375,11 @@ public class PolicyDBDaoTest { Assert.fail(); } PdpEntity pdp = (PdpEntity) pdps.get(0); - Assert.assertEquals(groupName, pdp.getGroup().getgroupName()); + Assert.assertEquals(groupName, pdp.getGroup().getGroupName()); Assert.assertEquals(pdp.getPdpName(), "primary"); session3.getTransaction().commit(); session3.close(); - group = dbd.getNewTransaction(); try { group.removePdpFromGroup("http://localhost:4344/pdp/", "testuser"); @@ -407,7 +407,7 @@ public class PolicyDBDaoTest { // add some pdps to groups group = dbd.getNewTransaction(); try { - group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser"); + group.createGroup(PolicyDbDao.createNewPdpGroupId("testgroup1"), "testgroup1", "test group", "testuser"); group.commitTransaction(); } catch (Exception e) { group.rollbackTransaction(); @@ -416,7 +416,7 @@ public class PolicyDBDaoTest { } group = dbd.getNewTransaction(); try { - group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser"); + group.createGroup(PolicyDbDao.createNewPdpGroupId("testgroup2"), "testgroup2", "test group", "testuser"); group.commitTransaction(); } catch (Exception e) { group.rollbackTransaction(); @@ -426,7 +426,7 @@ public class PolicyDBDaoTest { group = dbd.getNewTransaction(); try { - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDbDao.createNewPdpGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser"); group.commitTransaction(); } catch (Exception e) { @@ -436,7 +436,7 @@ public class PolicyDBDaoTest { } group = dbd.getNewTransaction(); try { - group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), + group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDbDao.createNewPdpGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser"); group.commitTransaction(); } catch (Exception e) { @@ -451,17 +451,16 @@ public class PolicyDBDaoTest { getPdp3.setParameter("deleted", false); List<?> pdps3 = getPdp3.list(); for (Object obj : pdps3) { - Assert.assertEquals("testgroup1", ((PdpEntity) obj).getGroup().getgroupName()); + Assert.assertEquals("testgroup1", ((PdpEntity) obj).getGroup().getGroupName()); } 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("/")); + 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) { @@ -491,21 +490,20 @@ public class PolicyDBDaoTest { getPdp4.setParameter("deleted", false); List<?> pdps4 = getPdp4.list(); for (Object obj : pdps4) { - Assert.assertEquals("testgroup2", ((PdpEntity) obj).getGroup().getgroupName()); + Assert.assertEquals("testgroup2", ((PdpEntity) obj).getGroup().getGroupName()); } session7.getTransaction().commit(); session7.close(); - group = dbd.getNewTransaction(); try { - OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/")); + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDbDao.createNewPdpGroupId("testgroup2"), Paths.get("/")); OnapPDPGroup groupToMoveTo = null; group.deleteGroup(groupToDelete, groupToMoveTo, "testuser"); group.commitTransaction(); Assert.fail(); - } catch (PolicyDBException pe) { + } catch (PolicyDbException pe) { // good, can't delete group with pdps group.rollbackTransaction(); } catch (Exception e) { @@ -566,12 +564,12 @@ public class PolicyDBDaoTest { + "******************************\n\n"); } - PolicyDBDaoTransaction t = dbd.getNewTransaction(); + 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; + 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 @@ -589,13 +587,12 @@ public class PolicyDBDaoTest { } 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"); } - PolicyDBDaoTransaction a = dbd.getNewTransaction(); + PolicyDbDaoTransaction a = dbd.getNewTransaction(); if (logger.isDebugEnabled()) { Date date = new java.util.Date(); logger.debug( @@ -607,7 +604,7 @@ public class PolicyDBDaoTest { 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; + 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 @@ -622,7 +619,7 @@ public class PolicyDBDaoTest { logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n b = dbd.getNewTransaction() " + "\n TimeStamp = " + date.getTime() + "\n\n"); } - PolicyDBDaoTransaction b = dbd.getNewTransaction(); + PolicyDbDaoTransaction b = dbd.getNewTransaction(); if (logger.isDebugEnabled()) { Date date = new java.util.Date(); logger.debug( @@ -639,14 +636,12 @@ public class PolicyDBDaoTest { 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"); + 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"); + System.setProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT, "5000"); // get a transacton - PolicyDBDaoTransaction t1 = dbd.getNewTransaction(); + PolicyDbDaoTransaction t1 = dbd.getNewTransaction(); if (logger.isDebugEnabled()) { Date date = new java.util.Date(); logger.debug( @@ -659,7 +654,7 @@ public class PolicyDBDaoTest { // 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 - PolicyDBDaoTransaction t2 = dbd2.getNewTransaction(); + 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 diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java new file mode 100644 index 000000000..8d8663e17 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import com.att.research.xacml.util.XACMLProperties; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +public class PolicyTest { + @Test + public void testPolicy() { + // Setup test data + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.pap.properties"); + PolicyRestAdapter adapter = Mockito.mock(PolicyRestAdapter.class); + Policy policy = new ConfigPolicy(adapter); + Path path = Paths.get("src/test/resources"); + + // Test set and get + policy.setFinalPolicyPath(path); + assertEquals(path, policy.getFinalPolicyPath()); + + // Test misc methods + assertNotNull(policy.createMatch("testKey", "testVal")); + assertNotNull(policy.createDynamicMatch("testKey", "testVal")); + assertNotNull(policy.getNextFilename(path, "Config", "SampleTest1206", 1)); + assertNull(policy.getNextLoopFilename(path, "Config", "ClosedLoop_PM", "foo", 1)); + assertNull(policy.getNextLoopFilename(path, "Config", "ClosedLoop_Fault", "foo", 1)); + assertNull(policy.getNextLoopFilename(path, "Config", "Micro Service", "foo", 1)); + assertNull(policy.getNextLoopFilename(path, "Config", "Optimization", "foo", 1)); + + // Test create + Object policyData = null; + assertEquals(0, policy.createPolicy(null, policyData).size()); + policyData = new PolicyType(); + assertEquals(1, policy.createPolicy(null, policyData).size()); + + // Test remaining set and get + assertNotNull(Policy.getConfigHome()); + assertEquals(true, policy.validateConfigForm()); + policy.setPreparedToSave(true); + assertEquals(true, policy.isPreparedToSave()); + policy.setPolicyExists(true); + assertEquals(true, policy.isPolicyExists()); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java index efb13b5a0..eccf13ba7 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -57,8 +58,8 @@ public class ActionPolicyDictionaryControllerTest { public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = Mockito.mock(CommonClassDao.class); - List<String> data = new ArrayList<>(); - List<Object> objectData = new ArrayList<>(); + List<String> data = new ArrayList<>(); + List<Object> objectData = new ArrayList<>(); data.add("Test"); UserInfo userInfo = new UserInfo(); @@ -71,9 +72,9 @@ public class ActionPolicyDictionaryControllerTest { actionData.setBody("Test"); assertTrue("Test".equals(actionData.getBody())); actionData.setCreatedDate(new Date()); - assertTrue(actionData.getCreatedDate()!= null); + assertTrue(actionData.getCreatedDate() != null); actionData.setModifiedDate(new Date()); - assertTrue(actionData.getModifiedDate()!= null); + assertTrue(actionData.getModifiedDate() != null); actionData.setHeader("Test"); assertTrue("Test".equals(actionData.getHeader())); actionData.setMethod("POST"); @@ -83,9 +84,9 @@ public class ActionPolicyDictionaryControllerTest { actionData.setUrl("http://test.com"); assertTrue("http://test.com".equals(actionData.getUrl())); actionData.setUserCreatedBy(userInfo); - assertTrue(actionData.getUserCreatedBy()!= null); + assertTrue(actionData.getUserCreatedBy() != null); actionData.setUserModifiedBy(userInfo); - assertTrue(actionData.getUserModifiedBy()!= null); + assertTrue(actionData.getUserModifiedBy() != null); objectData.add(actionData); when(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName")).thenReturn(data); @@ -95,7 +96,7 @@ public class ActionPolicyDictionaryControllerTest { controller = new ActionPolicyDictionaryController(); controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -103,60 +104,78 @@ public class ActionPolicyDictionaryControllerTest { } @Test - public void testGetActionEntitybyName(){ + public void testGetActionEntitybyName() { controller.getActionEntitybyName(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetActionPolicyDictionaryEntityData(){ + public void testGetActionPolicyDictionaryEntityData() { controller.getActionPolicyDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveActionPolicyDictionary(){ - jsonString = "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveActionPolicyDictionary() { + jsonString = + "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":" + + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\"," + + "\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"}," + + "\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateActionPolicyDictionary(){ - jsonString = "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateActionPolicyDictionary() { + jsonString = + "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":" + + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":" + + "\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"}," + + "\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveActionPolicyDictionary(){ - jsonString = "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\",\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"}}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemoveActionPolicyDictionary() { + jsonString = + "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":" + + "1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\"," + + "\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":" + + "{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\"," + + "\"userName\":\"Demo\"}}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java index d34e505ba..7d260907b 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -40,7 +41,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.mock.web.MockHttpServletResponse; @@ -61,14 +62,14 @@ public class BRMSDictionaryControllerTest { userInfo.setUserLoginId("testUserId"); userInfo.setUserName("John"); when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); - List<String> brms = new ArrayList<String>(); + List<String> brms = new ArrayList<String>(); brms.add("BRMS-Model"); - when(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "name")).thenReturn(brms); - doNothing().when(commonClassDao).delete(new BRMSParamTemplate()); - doNothing().when(commonClassDao).save(new BRMSParamTemplate()); + when(commonClassDao.getDataByColumn(BrmsParamTemplate.class, "name")).thenReturn(brms); + doNothing().when(commonClassDao).delete(new BrmsParamTemplate()); + doNothing().when(commonClassDao).save(new BrmsParamTemplate()); controller = new BRMSDictionaryController(); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -76,12 +77,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSParamDictionaryByNameEntityData(){ + public void testGetBRMSParamDictionaryByNameEntityData() { logger.info("testGetBRMSParamDictionaryByNameEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSParamDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -94,7 +96,8 @@ public class BRMSDictionaryControllerTest { logger.info("testGetBRMSParamDictionaryEntityData: Entering"); controller.getBRMSParamDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -105,14 +108,16 @@ public class BRMSDictionaryControllerTest { @Test public void testSaveBRMSParamDictionary() { logger.info("testSaveBRMSParamDictionary: Entering"); - jsonString = "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + jsonString = + "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveBRMSParamDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryData")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryData")); logger.info("response.getContentAsString(): " + response.getContentAsString()); - }catch(Exception e){ - logger.error("Exception"+ e); + } catch (Exception e) { + logger.error("Exception" + e); } logger.info("testSaveBRMSParamDictionary: exit"); } @@ -121,11 +126,12 @@ public class BRMSDictionaryControllerTest { public void testRemoveBRMSParamDictionary() { logger.info("testRemoveBRMSParamDictionary: Entering"); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSParamDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } @@ -133,12 +139,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSDependencyDictionaryByNameEntityData(){ + public void testGetBRMSDependencyDictionaryByNameEntityData() { logger.info("testGetBRMSDependencyDictionaryByNameEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSDependencyDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -147,12 +154,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSDependencyDictionaryEntityData(){ + public void testGetBRMSDependencyDictionaryEntityData() { logger.info("testGetBRMSDependencyDictionaryEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSDependencyDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -164,13 +172,16 @@ public class BRMSDictionaryControllerTest { @Test public void testSaveBRMSDependencyDictionary() { logger.info("testSaveBRMSDependencyDictionary: Entering"); - jsonString = "{\"brmsDependencyDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ - when(request.getReader()).thenReturn(br); - controller.saveBRMSDependencyDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryData")); - } catch (Exception e) { + jsonString = + "{\"brmsDependencyDictionaryData\": " + + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { + when(request.getReader()).thenReturn(br); + controller.saveBRMSDependencyDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryData")); + } catch (Exception e) { fail("Exception: " + e); } logger.info("testSaveBRMSDependencyDictionary: exit"); @@ -179,14 +190,15 @@ public class BRMSDictionaryControllerTest { @Test public void testRemoveBRMSDependencyDictionary() { logger.info("testRemoveBRMSDependencyDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSDependencyDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } @@ -194,13 +206,14 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSControllerDictionaryByNameEntityData(){ + public void testGetBRMSControllerDictionaryByNameEntityData() { logger.info("testGetBRMSControllerDictionaryByNameEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSControllerDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -209,13 +222,14 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSControllerDictionaryEntityData(){ + public void testGetBRMSControllerDictionaryEntityData() { logger.info("testGetBRMSControllerDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSControllerDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -227,14 +241,17 @@ public class BRMSDictionaryControllerTest { public void testSaveBRMSControllerDictionary() { logger.info("testSaveBRMSControllerDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - jsonString = "{\"brmsControllerDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + jsonString = + "{\"brmsControllerDictionaryData\": " + + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveBRMSControllerDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryData")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryData")); } catch (Exception e) { fail("Exception: " + e); } @@ -244,14 +261,15 @@ public class BRMSDictionaryControllerTest { @Test public void testRemoveBRMSControllerDictionary() { logger.info("testRemoveBRMSControllerDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSControllerDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -259,4 +277,3 @@ public class BRMSDictionaryControllerTest { logger.info("testRemoveBRMSControllerDictionary: exit"); } } - diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java index f530b4c62..8f0d52b21 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -41,10 +42,10 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ClosedLoopD2Services; import org.onap.policy.rest.jpa.ClosedLoopSite; -import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.PepOptions; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.rest.jpa.VNFType; -import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VnfType; +import org.onap.policy.rest.jpa.VsclAction; import org.onap.policy.rest.jpa.VarbindDictionary; import org.springframework.mock.web.MockHttpServletResponse; @@ -57,7 +58,7 @@ public class ClosedLoopDictionaryControllerTest { private ClosedLoopDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -71,14 +72,14 @@ public class ClosedLoopDictionaryControllerTest { userInfo.setUserLoginId("Test"); userInfo.setUserName("Test"); - doNothing().when(commonClassDao).delete(new VSCLAction()); - doNothing().when(commonClassDao).save(new VSCLAction()); + doNothing().when(commonClassDao).delete(new VsclAction()); + doNothing().when(commonClassDao).save(new VsclAction()); controller = new ClosedLoopDictionaryController(); controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -86,362 +87,404 @@ public class ClosedLoopDictionaryControllerTest { } @Test - public void testGetVSCLActionDictionaryByNameEntityData(){ - when(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction")).thenReturn(data); + public void testGetVSCLActionDictionaryByNameEntityData() { + when(commonClassDao.getDataByColumn(VsclAction.class, "vsclaction")).thenReturn(data); controller.getVSCLActionDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVSCLActionDictionaryEntityData(){ - when(commonClassDao.getData(VSCLAction.class)).thenReturn(new ArrayList<>()); + public void testGetVSCLActionDictionaryEntityData() { + when(commonClassDao.getData(VsclAction.class)).thenReturn(new ArrayList<>()); controller.getVSCLActionDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVNFTypeDictionaryByNameEntityData(){ - when(commonClassDao.getDataByColumn(VNFType.class, "vnftype")).thenReturn(data); + public void testGetVNFTypeDictionaryByNameEntityData() { + when(commonClassDao.getDataByColumn(VnfType.class, "vnftype")).thenReturn(data); controller.getVNFTypeDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVNFTypeDictionaryEntityData(){ - when(commonClassDao.getData(VNFType.class)).thenReturn(new ArrayList<>()); + public void testGetVNFTypeDictionaryEntityData() { + when(commonClassDao.getData(VnfType.class)).thenReturn(new ArrayList<>()); controller.getVNFTypeDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPEPOptionsDictionaryByNameEntityData(){ - when(commonClassDao.getDataByColumn(PEPOptions.class, "pepName")).thenReturn(data); + public void testGetPEPOptionsDictionaryByNameEntityData() { + when(commonClassDao.getDataByColumn(PepOptions.class, "pepName")).thenReturn(data); controller.getPEPOptionsDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPEPOptionsDictionaryEntityData(){ - when(commonClassDao.getData(PEPOptions.class)).thenReturn(new ArrayList<>()); + public void testGetPEPOptionsDictionaryEntityData() { + when(commonClassDao.getData(PepOptions.class)).thenReturn(new ArrayList<>()); controller.getPEPOptionsDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVarbindDictionaryByNameEntityData(){ + public void testGetVarbindDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName")).thenReturn(data); controller.getVarbindDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVarbindDictionaryEntityData(){ + public void testGetVarbindDictionaryEntityData() { when(commonClassDao.getData(VarbindDictionary.class)).thenReturn(new ArrayList<>()); controller.getVarbindDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopServiceDictionaryByNameEntityData(){ + public void testGetClosedLoopServiceDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName")).thenReturn(data); controller.getClosedLoopServiceDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopServiceDictionaryEntityData(){ + public void testGetClosedLoopServiceDictionaryEntityData() { when(commonClassDao.getData(ClosedLoopD2Services.class)).thenReturn(new ArrayList<>()); controller.getClosedLoopServiceDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopSiteDictionaryByNameEntityData(){ + public void testGetClosedLoopSiteDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName")).thenReturn(data); controller.getClosedLoopSiteDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopSiteDictionaryEntityData(){ + public void testGetClosedLoopSiteDictionaryEntityData() { when(commonClassDao.getData(ClosedLoopSite.class)).thenReturn(new ArrayList<>()); controller.getClosedLoopSiteDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveVSCLAction(){ - jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveVSCLAction() { + jsonString = + "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVSCLAction(){ - jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVSCLAction() { + jsonString = + "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVSCLAction(){ + public void testRemoveVSCLAction() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveVnfType(){ + public void testSaveVnfType() { jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVnfType(){ - jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVnfType() { + jsonString = + "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVnfType(){ + public void testRemoveVnfType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePEPOptions(){ - jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePEPOptions() { + jsonString = + "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePEPOptions(){ - jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePEPOptions() { + jsonString = + "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePEPOptions(){ - jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemovePEPOptions() { + jsonString = + "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveServiceType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveServiceType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateServiceType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateServiceType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveServiceType(){ + public void testRemoveServiceType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveSiteType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveSiteType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateSiteType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateSiteType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveSiteType(){ + public void testRemoveSiteType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveVarbind(){ - jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveVarbind() { + jsonString = + "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVarbind(){ - jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVarbind() { + jsonString = + "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVarbind(){ + public void testRemoveVarbind() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java index 1334f96a0..30d6d52bc 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.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) 2019 Samsung * ================================================================================ @@ -19,16 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; + import javax.servlet.http.HttpServletRequest; -import org.junit.After; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -39,8 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.springframework.mock.web.MockHttpServletResponse; public class DecisionPolicyDictionaryControllerTest { - private static Logger logger = - FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class); + private static Logger logger = FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class); private static CommonClassDao commonClassDao; private String jsonString = null; private HttpServletRequest request = null; @@ -52,19 +54,18 @@ public class DecisionPolicyDictionaryControllerTest { commonClassDao = Mockito.mock(CommonClassDao.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - jsonString = - "{\"attributeDictionaryDatas\": {\"error\": \"\",\"inprocess\": false,\"model\": " - + "{\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," - + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\"," - + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," - + "\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\",\"inprocess\": false,\"model\": " + + "{\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," + + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\"," + + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + + "\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); @@ -78,9 +79,6 @@ public class DecisionPolicyDictionaryControllerTest { logger.info("setUp: exit"); } - @After - public void tearDown() throws Exception {} - @Test public void testGetSettingsDictionaryByNameEntityData() { logger.info("testGetSettingsDictionaryByNameEntityData: Entering"); @@ -235,10 +233,9 @@ public class DecisionPolicyDictionaryControllerTest { try { // mock the getReader() call - jsonString = - "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\"" - + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\"," - + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}"; + jsonString = "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\"" + + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\"," + + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java index 0950b1cfd..f12299334 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -53,7 +54,7 @@ public class DescriptiveDictionaryControllerTest { private DescriptiveDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -74,15 +75,15 @@ public class DescriptiveDictionaryControllerTest { controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); logger.info("setUp: exit"); } - public List<Object> testDescriptiveScope(){ - List<Object> objectData = new ArrayList<>(); + public List<Object> testDescriptiveScope() { + List<Object> objectData = new ArrayList<>(); DescriptiveScope data = new DescriptiveScope(); data.setId(1); @@ -94,75 +95,89 @@ public class DescriptiveDictionaryControllerTest { data.setSearch("Test"); assertTrue("Test".equals(data.getSearch())); data.setCreatedDate(new Date()); - assertTrue(data.getCreatedDate()!= null); + assertTrue(data.getCreatedDate() != null); data.setModifiedDate(new Date()); - assertTrue(data.getModifiedDate()!= null); + assertTrue(data.getModifiedDate() != null); data.setUserCreatedBy(userInfo); - assertTrue(data.getUserCreatedBy()!= null); + assertTrue(data.getUserCreatedBy() != null); data.setUserModifiedBy(userInfo); - assertTrue(data.getUserModifiedBy()!= null); + assertTrue(data.getUserModifiedBy() != null); objectData.add(data); return objectData; } @Test - public void testGetDescriptiveDictionaryByNameEntityData(){ + public void testGetDescriptiveDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")).thenReturn(data); controller.getDescriptiveDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetDescriptiveDictionaryEntityData(){ + public void testGetDescriptiveDictionaryEntityData() { when(commonClassDao.getData(DescriptiveScope.class)).thenReturn(testDescriptiveScope()); controller.getDescriptiveDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveDescriptiveDictionary(){ - jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveDescriptiveDictionary() { + jsonString = + "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":" + + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\"," + + "\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateDescriptiveDictionary(){ - jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateDescriptiveDictionary() { + jsonString = + "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":" + + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\"," + + "\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveDescriptiveDictionary(){ - jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemoveDescriptiveDictionary() { + jsonString = + "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\"," + + "\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1," + + "\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java index 89be75f52..52b79b88f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.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. @@ -18,7 +18,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -70,12 +69,12 @@ public class DictionaryControllerTest { commonClassDao = Mockito.mock(CommonClassDao.class); MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("1707.4.1.2-Junit"); + testData.setVersion("1707.4.1.2-Junit"); - //--- mock the getDataByColumn() call - List<String> microList = new ArrayList<String>(); + // --- mock the getDataByColumn() call + List<String> microList = new ArrayList<String>(); microList.add("123"); - List<Object> listId = new ArrayList<Object>(); + List<Object> listId = new ArrayList<Object>(); when(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")).thenReturn(microList); List<Object> object = new ArrayList<>(); object.add(new Category()); @@ -83,9 +82,9 @@ public class DictionaryControllerTest { PolicyEditorScopes editorScope = new PolicyEditorScopes(); doNothing().when(commonClassDao).save(editorScope); doNothing().when(commonClassDao).update(editorScope); - + when(commonClassDao.getData(Attribute.class)).thenReturn(listId); - + request = mock(HttpServletRequest.class); controller = new DictionaryController(commonClassDao); new DictionaryUtils(commonClassDao); @@ -98,12 +97,13 @@ public class DictionaryControllerTest { public void testGetAttributeDictionaryEntityDatabyAttributeName() { logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getAttributeDictionaryEntityDatabyAttributeName(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -116,12 +116,13 @@ public class DictionaryControllerTest { public void testGetAttributeDictionaryEntityData() { logger.info("testGetAttributeDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getAttributeDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -134,16 +135,22 @@ public class DictionaryControllerTest { public void testSaveAttributeDictionary() { logger.info("testSaveAttributeDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - + try { - jsonString = "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":\"Qwerty\"},\"userid\":\"demo\"}"; + jsonString = + "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":" + + "\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":" + + "\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":" + + "\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":" + + "\"Qwerty\"},\"userid\":\"demo\"}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.saveAttributeDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -156,16 +163,17 @@ public class DictionaryControllerTest { public void testRemoveAttributeDictionary() { logger.info("testRemoveAttributeDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); try { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"xacmlId\":\"Test\"}}"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); + BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeAttributeDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -178,12 +186,13 @@ public class DictionaryControllerTest { public void testGetOnapNameDictionaryByNameEntityData() { logger.info("testGetOnapNameDictionaryByNameEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getOnapNameDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -196,12 +205,13 @@ public class DictionaryControllerTest { public void testGetOnapNameDictionaryEntityData() { logger.info("testGetOnapNameDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getOnapNameDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -215,16 +225,18 @@ public class DictionaryControllerTest { logger.info("testSaveOnapDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - + try { - jsonString = "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.saveOnapDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -237,16 +249,17 @@ public class DictionaryControllerTest { public void testRemoveOnapDictionary() { logger.info("testRemoveOnapDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); try { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"onapName\":\"Test\"}}"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); + BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeOnapDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java index 7ab1b170e..ee4dff803 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -42,7 +43,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; import org.springframework.mock.web.MockHttpServletResponse; -public class DictionaryImportControllerTest extends Mockito{ +public class DictionaryImportControllerTest extends Mockito { private static Logger logger = FlexLogger.getLogger(DictionaryImportController.class); @@ -59,20 +60,20 @@ public class DictionaryImportControllerTest extends Mockito{ controller = new DictionaryImportController(); new DictionaryImportController(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); } @Test - public void testIsValidDictionaryName(){ + public void testIsValidDictionaryName() { DictionaryImportController cotroller = new DictionaryImportController(); - //test invalid name + // test invalid name assertTrue(!cotroller.isValidDictionaryName("wrong-name")); - //test valid name + // test valid name assertTrue(cotroller.isValidDictionaryName("ActionList")); } @Test - public void testImportDictionaryData() throws ServletException, IOException{ + public void testImportDictionaryData() throws ServletException, IOException { List<String> fileNames = new ArrayList<>(); fileNames.add("Attribute.csv"); fileNames.add("ActionPolicyDictionary.csv"); @@ -95,13 +96,13 @@ public class DictionaryImportControllerTest extends Mockito{ fileNames.add("SearchCriteria.csv"); fileNames.add("VNFType.csv"); fileNames.add("VSCLAction.csv"); - fileNames.add("PEPOptions.csv"); + fileNames.add("PepOptions.csv"); fileNames.add("Settings.csv"); fileNames.add("Zone.csv"); fileNames.add("ActionList.csv"); - for(int i =0; i < fileNames.size(); i++){ - File file = new File("src/test/resources/dictionaryImport/"+fileNames.get(i)); - try(FileInputStream targetStream = new FileInputStream(file)){ + for (int i = 0; i < fileNames.size(); i++) { + File file = new File("src/test/resources/dictionaryImport/" + fileNames.get(i)); + try (FileInputStream targetStream = new FileInputStream(file)) { PushPolicyControllerTest pushController = new PushPolicyControllerTest(); when(request.getInputStream()).thenReturn(pushController.getInputStream(getBytes(targetStream))); when(request.getParameter("userId")).thenReturn("demo"); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java index 45d8466b6..3359a7aed 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -46,8 +47,8 @@ import org.onap.policy.rest.adapter.Term; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.AddressGroup; -import org.onap.policy.rest.jpa.FWTag; -import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.FwTag; +import org.onap.policy.rest.jpa.FwTagPicker; import org.onap.policy.rest.jpa.FirewallDictionaryList; import org.onap.policy.rest.jpa.GroupServiceList; import org.onap.policy.rest.jpa.PortList; @@ -117,7 +118,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetProtocolListDictionaryEntityDataByName() { - test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", + test_WithGetDataByColumn(ProtocolList.class, + "protocolListDictionaryDatas", "protocolName", () -> controller.getProtocolListDictionaryEntityDataByName(response)); } @@ -195,7 +197,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetZoneDictionaryEntityData() { - test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response)); + test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> + controller.getZoneDictionaryEntityData(response)); } @Test @@ -212,7 +215,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetFWDictListDictionaryEntityDataByName() { - test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", + test_WithGetDataByColumn(FirewallDictionaryList.class, + "fwDictListDictionaryDatas", "parentItemName", () -> controller.getFWDictListDictionaryEntityDataByName(response)); } @@ -224,37 +228,41 @@ public class FirewallDictionaryControllerTest { @Test public void testGetTagPickerNameEntityDataByName() { - test_WithGetDataByColumn(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", + test_WithGetDataByColumn(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", () -> controller.getTagPickerNameEntityDataByName(response)); } @Test public void testGetTagPickerDictionaryEntityData() { - test_WithGetData(FWTagPicker.class, "fwTagPickerDictionaryDatas", + test_WithGetData(FwTagPicker.class, "fwTagPickerDictionaryDatas", () -> controller.getTagPickerDictionaryEntityData(response)); } @Test public void testGetTagNameEntityDataByName() { - test_WithGetDataByColumn(FWTag.class, "fwTagDictionaryDatas", "fwTagName", + test_WithGetDataByColumn(FwTag.class, "fwTagDictionaryDatas", "fwTagName", () -> controller.getTagNameEntityDataByName(response)); } @Test public void testGetTagDictionaryEntityData() { - test_WithGetData(FWTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response)); + test_WithGetData(FwTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response)); } @Test public void testSavePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"description\":\"test\",\"prefixListName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":" + + "{\"description\":\"test\",\"prefixListName\":\"Test\"}}"; testSave(PrefixList.class, "prefixListDictionaryDatas", "prefixListName", () -> controller.savePrefixListDictionary(request, response)); } @Test public void testUpdatePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"prefixListName\":\"Test\"}}"; testUpdate(PrefixList.class, "prefixListDictionaryDatas", "prefixListName", () -> controller.savePrefixListDictionary(request, response)); } @@ -268,20 +276,25 @@ public class FirewallDictionaryControllerTest { @Test public void testValidatePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}"; testValidate(PrefixList.class, "result", () -> controller.validatePrefixListDictionary(request, response)); } @Test public void testSavePortListDictionary() { - jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}"; testSave(PortList.class, "portListDictionaryDatas", "portName", () -> controller.savePortListDictionary(request, response)); } @Test public void testUpdatePortListDictionary() { - jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"portName\":\"Test\"}}"; testUpdate(PortList.class, "portListDictionaryDatas", "portName", () -> controller.savePortListDictionary(request, response)); } @@ -295,14 +308,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveProtocolListDictionary() { - jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":" + + "\"Test\"}}"; testSave(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", () -> controller.saveProtocolListDictionary(request, response)); } @Test public void testUpdateProtocolListDictionary() { - jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"protocolName\":\"Test\"}}"; testUpdate(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", () -> controller.saveProtocolListDictionary(request, response)); } @@ -316,14 +333,20 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveAddressGroupDictionary() { - jsonString = "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":" + + "\"Test\"},\"userid\":\"demo\"}"; testSave(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveAddressGroupDictionary(request, response)); } @Test public void testUpdateAddressGroupDictionary() { - jsonString = "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testUpdate(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveAddressGroupDictionary(request, response)); } @@ -337,14 +360,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveActionListDictionary() { - jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":" + + "\"Test\"}}"; testSave(ActionList.class, "actionListDictionaryDatas", "actionName", () -> controller.saveActionListDictionary(request, response)); } @Test public void testUpdateActionListDictionary() { - jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":" + + "\"Test\"}}"; testUpdate(ActionList.class, "actionListDictionaryDatas", "actionName", () -> controller.saveActionListDictionary(request, response)); } @@ -358,14 +385,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveServiceGroupDictionary() { - jsonString = "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; testSave(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveServiceGroupDictionary(request, response)); } @Test public void testUpdateServiceGroupDictionary() { - jsonString = "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; testUpdate(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveServiceGroupDictionary(request, response)); } @@ -379,14 +410,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveSecurityZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":" + + "\"Test\"}}"; testSave(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName", () -> controller.saveSecurityZoneDictionary(request, response)); } @Test public void testUpdateSecurityZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":" + + "\"Test\"}}"; testUpdate(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName", () -> controller.saveSecurityZoneDictionary(request, response)); } @@ -400,21 +435,33 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveServiceListDictionary() { - jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":" + + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; testSave(ServiceList.class, "serviceListDictionaryDatas", "serviceName", () -> controller.saveServiceListDictionary(request, response)); } @Test public void testUpdateServiceListDictionary() { - jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":" + + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; testUpdate(ServiceList.class, "serviceListDictionaryDatas", "serviceName", () -> controller.saveServiceListDictionary(request, response)); } @Test public void testRemoveServiceListDictionary() { - jsonString = "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":" + + "\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testRemove(ServiceList.class, "serviceListDictionaryDatas", () -> controller.removeServiceListDictionary(request, response)); } @@ -422,12 +469,14 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveZoneDictionary() { jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; - testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response)); + testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () + -> controller.saveZoneDictionary(request, response)); } @Test public void testUpdateZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; testUpdate(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response)); } @@ -440,14 +489,34 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveTermListDictionary() { - jsonString = "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":" + + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":" + + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":" + + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":" + + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":" + + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":" + + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testSave(TermList.class, "termListDictionaryDatas", "termName", () -> controller.saveTermListDictionary(request, response)); } @Test public void testUpdateTermListDictionary() { - jsonString = "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":" + + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":" + + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":" + + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":" + + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":" + + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":" + + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testUpdate(TermList.class, "termListDictionaryDatas", "termName", () -> controller.saveTermListDictionary(request, response)); } @@ -461,14 +530,22 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveFWDictionaryList() { - jsonString = "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testSave(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", () -> controller.saveFWDictionaryList(request, response)); } @Test public void testUpdateFWDictionaryList() { - jsonString = "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testUpdate(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", () -> controller.saveFWDictionaryList(request, response)); } @@ -482,43 +559,53 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveFirewallTagPickerDictionary() { - jsonString = "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; - testSave(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", + jsonString = + "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":" + + "\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; + testSave(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", () -> controller.saveFirewallTagPickerDictionary(request, response)); } @Test public void testUpdateFirewallTagPickerDictionary() { - jsonString = "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; - testUpdate(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", + jsonString = + "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":" + + "\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":" + + "\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + testUpdate(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", () -> controller.saveFirewallTagPickerDictionary(request, response)); } @Test public void testRemoveFirewallTagPickerDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"tagPickerName\":\"Test\"}}"; - testRemove(FWTagPicker.class, "fwTagPickerDictionaryDatas", + testRemove(FwTagPicker.class, "fwTagPickerDictionaryDatas", () -> controller.removeFirewallTagPickerDictionary(request, response)); } @Test public void testSaveFirewallTagDictionary() { - jsonString = "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; - testSave(FWTag.class, "fwTagDictionaryDatas", "fwTagName", + jsonString = + "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":" + + "\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; + testSave(FwTag.class, "fwTagDictionaryDatas", "fwTagName", () -> controller.saveFirewallTagDictionary(request, response)); } @Test public void testUpdateFirewallTagDictionary() { - jsonString = "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; - testUpdate(FWTag.class, "fwTagDictionaryDatas", "fwTagName", + jsonString = + "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":" + + "[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; + testUpdate(FwTag.class, "fwTagDictionaryDatas", "fwTagName", () -> controller.saveFirewallTagDictionary(request, response)); } @Test public void testRemoveFirewallTagDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\"}}"; - testRemove(FWTag.class, "fwTagDictionaryDatas", + testRemove(FwTag.class, "fwTagDictionaryDatas", () -> controller.removeFirewallTagDictionary(request, response)); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java index e561a65b2..115e30249 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java @@ -20,7 +20,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -28,12 +27,15 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -41,7 +43,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.DcaeUuid; import org.onap.policy.rest.jpa.MicroServiceLocation; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.UserInfo; @@ -75,7 +77,7 @@ public class MicroServiceDictionaryControllerTest { List<String> listIds = new ArrayList<String>(); listIds.add("Jack"); - when(commonClassDao.getDataByColumn(DCAEuuid.class, "name")).thenReturn(listIds); + when(commonClassDao.getDataByColumn(DcaeUuid.class, "name")).thenReturn(listIds); List<String> microList = new ArrayList<String>(); microList.add("MC-Model"); @@ -83,7 +85,7 @@ public class MicroServiceDictionaryControllerTest { List<Object> listId = new ArrayList<Object>(); listId.add("smith"); - when(commonClassDao.getData(DCAEuuid.class)).thenReturn(listId); + when(commonClassDao.getData(DcaeUuid.class)).thenReturn(listId); MicroServiceModels microServiceModels = new MicroServiceModels(); doNothing().when(commonClassDao).delete(microServiceModels); @@ -141,7 +143,6 @@ public class MicroServiceDictionaryControllerTest { logger.info("testSaveMicroServiceHeaderDefaultValues: exit"); } - @Test public void testGetMicroServiceHeaderDefaultsEntityDataByName() { logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering"); @@ -215,7 +216,6 @@ public class MicroServiceDictionaryControllerTest { logger.info("testRemoveMicroServiceHeaderDefaults: exit"); } - @Test public void testGetDCAEUUIDDictionaryByNameEntityData() { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java index 5e0b7ce28..f109dbdda 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java @@ -2,7 +2,7 @@ * ============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 * ================================================================================ @@ -19,19 +19,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + +import com.mockrunner.mock.web.MockHttpServletRequest; import java.io.BufferedReader; import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -39,14 +43,10 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DCAEuuid; -import org.onap.policy.rest.jpa.MicroServiceLocation; -import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.mock.web.MockHttpServletResponse; - public class OptimizationDictionaryControllerTest { private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class); @@ -63,8 +63,7 @@ public class OptimizationDictionaryControllerTest { UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId("testUserId"); userInfo.setUserName("John"); - when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")) - .thenReturn(userInfo); + when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); OptimizationModels optimziationModels = new OptimizationModels(); @@ -76,19 +75,17 @@ public class OptimizationDictionaryControllerTest { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - jsonString = - "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\",\"inprocess\": false,\"model\":" - + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," - + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," - + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," - + "\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + jsonString = "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\",\"inprocess\": false,\"model\":" + + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," + + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," + + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + "\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; br = new BufferedReader(new StringReader(jsonString)); // --- mock the getReader() call @@ -115,7 +112,7 @@ public class OptimizationDictionaryControllerTest { controller.getOptimizationModelsDictionaryEntityData(response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -137,7 +134,7 @@ public class OptimizationDictionaryControllerTest { controller.saveOptimizationModelsDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -156,28 +153,58 @@ public class OptimizationDictionaryControllerTest { try { // mock the getReader() call jsonString = - "{\"data\": {\"modelName\": \"test\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\"," - + "\"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," - + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," - + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + "{\"data\": {\"modelName\": \"test\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\"," + + "\"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," + + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," + + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeOptimizationModelsDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } logger.info("testRemoveOptimizationModelsDictionary: exit"); } + + @Test + public void testGet() { + OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao); + MockHttpServletResponse response = new MockHttpServletResponse(); + controller.getOptimizationModelsDictionaryByNameEntityData(response); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void testSave() { + OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao); + MockHttpServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + req.setBodyContent("{\n\"modelType\": \"type.yml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", " + + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, " + + "\"classMap\": \"{\\\"dep\\\":\\\"{\\\"dependency\\\":\\\"depval\\\"}\\\"}\" }\n"); + assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response)) + .isInstanceOf(NullPointerException.class); + + req.setBodyContent("{\n\"modelType\": \"type.xml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", " + + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, " + + "\"classMap\": \"{\\\"dep\\\": {\\\"dependency\\\":\\\"depval\\\"} }\" }\n"); + assertThatCode(() -> controller.saveOptimizationModelsDictionary(req, response)).doesNotThrowAnyException(); + + req.setupAddParameter("apiflag", "api"); + assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response)) + .isInstanceOf(NullPointerException.class); + } + } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java index 9bf2ae590..f8273493b 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -55,7 +56,7 @@ public class PolicyScopeDictionaryControllerTest { private PolicyScopeDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -76,7 +77,7 @@ public class PolicyScopeDictionaryControllerTest { controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -84,302 +85,339 @@ public class PolicyScopeDictionaryControllerTest { } @Test - public void testGetGroupPolicyScopeEntityDataByName(){ + public void testGetGroupPolicyScopeEntityDataByName() { when(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name")).thenReturn(data); controller.getGroupPolicyScopeEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetGroupPolicyScopeEntityData(){ + public void testGetGroupPolicyScopeEntityData() { when(commonClassDao.getData(GroupPolicyScopeList.class)).thenReturn(new ArrayList<>()); controller.getGroupPolicyScopeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSClosedLoopEntityDataByName(){ + public void testGetPSClosedLoopEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name")).thenReturn(data); controller.getPSClosedLoopEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSClosedLoopEntityData(){ + public void testGetPSClosedLoopEntityData() { when(commonClassDao.getData(PolicyScopeClosedLoop.class)).thenReturn(new ArrayList<>()); controller.getPSClosedLoopEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSServiceEntityDataByName(){ + public void testGetPSServiceEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeService.class, "name")).thenReturn(data); controller.getPSServiceEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSServiceEntityData(){ + public void testGetPSServiceEntityData() { when(commonClassDao.getData(PolicyScopeService.class)).thenReturn(new ArrayList<>()); controller.getPSServiceEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSTypeEntityDataByName(){ + public void testGetPSTypeEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeType.class, "name")).thenReturn(data); controller.getPSTypeEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSTypeEntityData(){ + public void testGetPSTypeEntityData() { when(commonClassDao.getData(PolicyScopeType.class)).thenReturn(new ArrayList<>()); controller.getPSTypeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSResourceEntityDataByName(){ + public void testGetPSResourceEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name")).thenReturn(data); controller.getPSResourceEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSResourceEntityData(){ + public void testGetPSResourceEntityData() { when(commonClassDao.getData(PolicyScopeResource.class)).thenReturn(new ArrayList<>()); controller.getPSResourceEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSavePSGroupScopeDictionary(){ - jsonString = "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSGroupScopeDictionary() { + jsonString = + "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSGroupScopeDictionary(){ - jsonString = "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSGroupScopeDictionary() { + jsonString = + "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":" + + "\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":" + + "\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSGroupScopeDictionary(){ + public void testRemovePSGroupScopeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSClosedLoopDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSClosedLoopDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSClosedLoopDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSClosedLoopDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSClosedLoopDictionary(){ + public void testRemovePSClosedLoopDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSServiceDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSServiceDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSServiceDictionary(){ + public void testUpdatePSServiceDictionary() { jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSServiceDictionary(){ + public void testRemovePSServiceDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSTypeDictionary(){ + public void testSavePSTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSTypeDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSTypeDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSTypeDictionary(){ + public void testRemovePSTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSResourceDictionary(){ + public void testSavePSResourceDictionary() { jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSResourceDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSResourceDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSResourceDictionary(){ + public void testRemovePSResourceDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } 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 007d02120..f9711b9ed 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 @@ -22,7 +22,9 @@ 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; @@ -32,12 +34,14 @@ 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; @@ -52,7 +56,6 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyVersion; import org.springframework.mock.web.MockServletConfig; - public class PushPolicyControllerTest { private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class); @@ -68,7 +71,7 @@ public class PushPolicyControllerTest { @BeforeClass public static void beforeClassSetup() throws ServletException { - sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest"); + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest"); } @Before @@ -82,7 +85,8 @@ public class PushPolicyControllerTest { servletConfig = Mockito.mock(MockServletConfig.class); 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"); + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("src/test/resources/xacml.pap.properties"); commonClassDao = Mockito.mock(CommonClassDao.class); controller = new PushPolicyController(); @@ -91,35 +95,39 @@ public class PushPolicyControllerTest { } @Test - public void testPushPolicy() throws ServletException, PAPException{ + public void testPushPolicy() throws ServletException, PAPException { PolicyVersion versionData = new PolicyVersion(); - versionData.setPolicyName("com"+File.separator+"Config_Test"); + versionData.setPolicyName("com" + File.separator + "Config_Test"); versionData.setActiveVersion(1); versionData.setHigherVersion(1); List<Object> data = new ArrayList<>(); data.add(versionData); - when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(data); + when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test")) + .thenReturn(data); pap = new XACMLPapServlet(); pap.init(servletConfig); callPushPolicy(); - when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(null); + when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test")) + .thenReturn(null); callPushPolicy(); } - public void callPushPolicy(){ - jsonString = "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void callPushPolicy() { + jsonString = + "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { char[] charBuffer = new char[8 * 1024]; StringBuilder builder = new StringBuilder(); int numCharsRead; while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) { builder.append(charBuffer, 0, numCharsRead); } - when(request.getInputStream()).thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8))); + when(request.getInputStream()) + .thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8))); controller.pushPolicy(request, response); assertTrue(response != null); - }catch(Exception e){ - logger.error("Exception"+ e); + } catch (Exception e) { + logger.error("Exception" + e); } } @@ -148,9 +156,9 @@ public class PushPolicyControllerTest { return servletInputStream; } - @After - public void destroy(){ - if(pap!=null) - pap.destroy(); - } + @After + public void destroy() { + if (pap != null) + pap.destroy(); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java index ae1840ebb..8292704b8 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -53,7 +54,7 @@ public class SafePolicyControllerTest { private SafePolicyController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -76,127 +77,139 @@ public class SafePolicyControllerTest { DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); logger.info("setUp: exit"); } @Test - public void testGetRiskTypeDictionaryByNameEntityData(){ + public void testGetRiskTypeDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(RiskType.class, "name")).thenReturn(data); controller.getRiskTypeDictionaryByNameEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetRiskTypeDictionaryEntityData(){ + public void testGetRiskTypeDictionaryEntityData() { when(commonClassDao.getData(RiskType.class)).thenReturn(new ArrayList<>()); controller.getRiskTypeDictionaryEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetSafePolicyWarningEntityDataByName(){ + public void testGetSafePolicyWarningEntityDataByName() { when(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")).thenReturn(data); controller.getSafePolicyWarningEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetSafePolicyWarningeEntityData(){ + public void testGetSafePolicyWarningeEntityData() { when(commonClassDao.getData(SafePolicyWarning.class)).thenReturn(new ArrayList<>()); controller.getSafePolicyWarningeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveRiskTypeDictionary(){ - jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveRiskTypeDictionary() { + jsonString = + "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateRiskTypeDictionary(){ + public void testUpdateRiskTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveRiskTypeDictionary(){ + public void testRemoveRiskTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveSafePolicyWarningDictionary(){ - jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveSafePolicyWarningDictionary() { + jsonString = + "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateSafePolicyWarningDictionary(){ + public void testUpdateSafePolicyWarningDictionary() { jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveSafePolicyWarningDictionary(){ + public void testRemoveSafePolicyWarningDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java index da9c4e8f5..2b95be068 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.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,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertTrue; @@ -46,21 +47,21 @@ public class ElasticSearchPolicyUpdateTest { private XACMLPAPTest papTest; @Before - public void setUp() throws IOException, ServletException, SQLException{ + public void setUp() throws IOException, ServletException, SQLException { // Set the system property temporarily System.setProperty("PROPERTY_FILE", "src/test/resources/policyelk.properties"); try { ClassLoader classLoader = getClass().getClassLoader(); policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { - logger.error("Exception Occured"+e1); + logger.error("Exception Occured" + e1); } papTest = new XACMLPAPTest(); papTest.setDBDao(); } @Test - public void testElasticSearchMainFunction() throws SQLException{ + public void testElasticSearchMainFunction() throws SQLException { ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity(); configurationEntity.setConfigBody("Sample Test"); configurationEntity.setConfigType("OTHER"); @@ -68,8 +69,7 @@ public class ElasticSearchPolicyUpdateTest { configurationEntity.setDescription("test"); configurationEntity.setModifiedBy("Test"); configurationEntity.setModifiedDate(new Date()); - - + PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyContent.toString()); @@ -91,7 +91,7 @@ public class ElasticSearchPolicyUpdateTest { } @After - public void reset(){ + public void reset() { System.clearProperty("PROPERTY_FILE"); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java new file mode 100644 index 000000000..145873981 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.elk; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector; +import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyBodyType; +import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; +import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyType; + +public class ElkConnectorTest { + @Test + public void testConnector() { + PolicyType type = PolicyType.Config; + PolicyBodyType body = PolicyBodyType.json; + assertNotNull(type); + assertNotNull(body); + + assertEquals(PolicyIndexType.closedloop, ElkConnector.toPolicyIndexType("Config_Fault")); + assertEquals(PolicyIndexType.closedloop, ElkConnector.toPolicyIndexType("Config_PM")); + assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_FW")); + assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_MS")); + assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_OOF")); + assertEquals(PolicyIndexType.action, ElkConnector.toPolicyIndexType("Action")); + assertEquals(PolicyIndexType.decision, ElkConnector.toPolicyIndexType("Decision")); + assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config")); + + assertThatIllegalArgumentException().isThrownBy(() -> ElkConnector.toPolicyIndexType(null)); + + assertThatIllegalArgumentException().isThrownBy(() -> ElkConnector.toPolicyIndexType("Foo")); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java index 0b8c86c1e..7d6b90831 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.Pair; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java index 76c0ce788..401e419bb 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.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. @@ -21,9 +21,11 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticData; import org.onap.policy.rest.adapter.PolicyRestAdapter; @@ -103,7 +105,7 @@ public class PolicyElasticDataTest { data.setSupressionType(testVal); assertEquals(data.getSupressionType(), testVal); data.setServiceType(testVal); - assertEquals(data.getServiceType(),testVal); + assertEquals(data.getServiceType(), testVal); data.setUuid(testVal); assertEquals(data.getUuid(), testVal); data.setLocation(testVal); @@ -111,7 +113,7 @@ public class PolicyElasticDataTest { data.setPriority(testVal); assertEquals(data.getPriority(), testVal); data.setMsLocation(testVal); - assertEquals(data.getMsLocation(),testVal); + assertEquals(data.getMsLocation(), testVal); data.setRuleName(testVal); assertEquals(data.getRuleName(), testVal); data.setBrmsParamBody(testMap); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java index bdbe1441d..38102afb0 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.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,39 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.when; import java.io.BufferedReader; +import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; - +import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.springframework.mock.web.MockHttpServletResponse; public class PolicyElasticSearchControllerTest { - private PolicyElasticSearchController conroller; + private PolicyElasticSearchController controller; private HttpServletRequest request = null; private HttpServletResponse response = null; @Before - public void setup(){ - conroller = new PolicyElasticSearchController(); + public void setup() { + controller = new PolicyElasticSearchController(); request = Mockito.mock(HttpServletRequest.class); - response = Mockito.mock(HttpServletResponse.class); + response = new MockHttpServletResponse(); } @Test - public void testSearchDictionary(){ + public void testSearchDictionary() throws IOException { List<String> jsonString = new ArrayList<>(); jsonString.add("{\"type\":\"attribute\",\"data\":{\"xacmlId\":\"Test\"}}"); jsonString.add("{\"type\":\"onapName\",\"data\":{\"onapName\":\"Test\"}}"); @@ -69,13 +78,36 @@ public class PolicyElasticSearchControllerTest { jsonString.add("{\"type\":\"psGroupPolicy\",\"data\":{\"name\":\"Test\"}}"); jsonString.add("{\"type\":\"safeRisk\",\"data\":{\"name\":\"Test\"}}"); jsonString.add("{\"type\":\"safePolicyWarning\",\"data\":{\"name\":\"Test\"}}"); - for(int i = 0; i < jsonString.size(); i++){ - try(BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) { - when(request.getReader()).thenReturn(br); - conroller.searchDictionary(request, response); - } catch (Exception e) { - assertEquals(NullPointerException.class, e.getClass()); - } + for (int i = 0; i < jsonString.size(); i++) { + BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i))); + when(request.getReader()).thenReturn(br); + assertThatCode(() -> controller.searchDictionary(request, response)).doesNotThrowAnyException(); } } + + @Test + public void testController() throws IOException { + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + PolicyElasticSearchController controller = new PolicyElasticSearchController(dao); + assertEquals(PolicyIndexType.all, controller.toPolicyIndexType(null)); + assertEquals(PolicyIndexType.config, controller.toPolicyIndexType("config")); + + Map<String, String> searchKeys = new HashMap<String, String>(); + searchKeys.put("key", "value"); + assertThatThrownBy(() -> controller.search(PolicyIndexType.config, "text", searchKeys)) + .isInstanceOf(Exception.class); + + when(request.getParameter("policyName")).thenReturn("policyName"); + when(request.getParameter("action")).thenReturn("search"); + when(request.getReader()) + .thenReturn(new BufferedReader(new StringReader("{\"searchdata\": { \"query\": \"value space\", " + + "\"policyType\": \"all\", " + "\"closedLooppolicyType\": \"type\", " + "\"onapName\": \"pef\", " + + "\"vnfType\": \"vnf\", " + "\"policyStatus\": \"active\", " + "\"vproAction\": \"reboot\", " + + "\"serviceType\": \"type\", " + "\"bindTextSearch\": \"pef\", " + "\"d2Service\": \"vDNS\"} }"))); + controller.searchPolicy(request, response); + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + + PolicyRestAdapter policyData = new PolicyRestAdapter(); + assertFalse(controller.deleteElk(policyData)); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java index 7df295382..bffdf3d79 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.PolicyLocator; @@ -35,8 +36,7 @@ public class PolicyLocatorTest { String version = "1.0"; String testString = "[owner|scope|type|name|id|v1.0|]"; - PolicyLocator locator = new PolicyLocator(policyType, policyName, owner, - scope, policyId, version); + PolicyLocator locator = new PolicyLocator(policyType, policyName, owner, scope, policyId, version); String locatorString = locator.toString(); assertEquals(locatorString, testString); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImplTest.java index 2f3d580f7..8eb003ca8 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImplTest.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. @@ -18,23 +18,24 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.xacml.rest.elk; +package org.onap.policy.pap.xacml.rest.elk.client; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import io.searchbox.client.JestResult; +import io.searchbox.client.JestResult; import java.io.IOException; import java.lang.reflect.Method; - +import java.util.HashMap; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; -import org.onap.policy.pap.xacml.rest.elk.client.ElkConnectorImpl; import org.onap.policy.rest.adapter.PolicyRestAdapter; public class ElkConnectorImplTest { @@ -56,41 +57,41 @@ public class ElkConnectorImplTest { } @Test - public void searchTest(){ - JestResult r1=null, r2=null, r3=null, r4=null; + public void searchTest() { + JestResult r1 = null, r2 = null, r3 = null, r4 = null; // Should always work if the above test passes and ELK server is up - try{ + try { r1 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123"); } catch (Exception e) { // ELK server is down. Don't continue the test - if(e instanceof IllegalStateException){ + if (e instanceof IllegalStateException) { return; } fail(); } // Should always work - try{ + try { r2 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The_quick_brown_fox_jumps_over_the_lazy_dog"); } catch (Exception e) { fail(); } // Should throw exception - try{ + try { r3 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123{}"); } catch (Exception e) { - if(! (e instanceof IllegalArgumentException)){ + if (!(e instanceof IllegalArgumentException)) { fail(); } } // Should throw exception - try{ + try { r4 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The quick brown fox jumps over the lazy dog"); } catch (Exception e) { - if(! (e instanceof IllegalArgumentException)){ + if (!(e instanceof IllegalArgumentException)) { fail(); } } @@ -114,7 +115,6 @@ public class ElkConnectorImplTest { fail("Expected exception to be thrown"); } - @Test public void testPut() throws IOException { thrown.expect(NullPointerException.class); @@ -143,4 +143,31 @@ public class ElkConnectorImplTest { impl.search(PolicyIndexType.config, "search", null); fail("Expected exception to be thrown"); } + + @Test + public void testImplNegCases() throws IOException { + ElkConnectorImpl impl = new ElkConnectorImpl(); + Map<String, String> filter = new HashMap<String, String>(); + assertThatThrownBy(() -> impl.isType(PolicyIndexType.config)).isInstanceOf(IOException.class); + assertThatThrownBy(() -> impl.isIndex()).isInstanceOf(IOException.class); + assertThatThrownBy(() -> impl.search(null, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> impl.search(null, "")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> impl.search(null, ";;;")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> impl.search(null, "foo")).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> impl.search(PolicyIndexType.all, "foo")).isInstanceOf(IllegalStateException.class); + + assertThatThrownBy(() -> impl.search(null, null, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> impl.search(null, null, filter)).isInstanceOf(IllegalArgumentException.class); + filter.put("key", "value"); + assertThatThrownBy(() -> impl.search(null, ";;;", filter)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> impl.search(null, "foo", filter)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> impl.search(PolicyIndexType.config, "foo", filter)) + .isInstanceOf(IllegalStateException.class); + + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setNewFileName("scope.Decision_newFile"); + adapter.setConfigPolicyType("Config"); + assertThatThrownBy(() -> impl.put(adapter)).isInstanceOf(IOException.class); + assertThatThrownBy(() -> impl.delete(adapter)).isInstanceOf(IllegalStateException.class); + } } 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 008f2629e..885230da4 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,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,15 @@ package org.onap.policy.pap.xacml.rest.handler; 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.Matchers.any; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; + import com.mockrunner.mock.web.MockHttpServletRequest; import com.mockrunner.mock.web.MockHttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.hibernate.Session; @@ -41,14 +45,19 @@ 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.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.policy.xacml.std.pap.StdEngine; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) +@PrepareForTest(DeleteHandler.class) public class DeleteHandlerTest { @Before public void setUp() { @@ -93,31 +102,114 @@ public class DeleteHandlerTest { PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class); PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller); - // 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(); + handler.doApiDeleteFromPap(request, response); // Test deletion from PDP OnapLoggingContext loggingContext = Mockito.mock(OnapLoggingContext.class); - try { - handler.doApiDeleteFromPdp(request, response, loggingContext); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } - - // Test delete entity - PolicyEntity policyEntity = new PolicyEntity(); - policyEntity.setPolicyName("testVal"); - String result = DeleteHandler.deletePolicyEntityData(policyEntity); - assertEquals(result, "success"); - - // Test check entity - List<?> peResult = Collections.emptyList(); - assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false); - } + handler.doApiDeleteFromPdp(request, response, loggingContext); + + // Test delete entity + PolicyEntity policyEntity = new PolicyEntity(); + policyEntity.setPolicyName("testVal"); + String result = DeleteHandler.deletePolicyEntityData(policyEntity); + assertEquals(result, "success"); + + // Test check entity + List<?> peResult = Collections.emptyList(); + assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false); + } + + @Test + public void testDoDeletePap() throws IOException { + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + DeleteHandler handler = new DeleteHandler(dao); + + // Request #1 + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + MockHttpServletResponse response = new MockHttpServletResponse(); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #2 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #3 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #4 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Bar_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #5 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #6 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #7 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Mock dao + List<PolicyVersion> pePVs = new ArrayList<PolicyVersion>(); + PolicyVersion pv = new PolicyVersion(); + pePVs.add(pv); + List<Object> peObjs = new ArrayList<Object>(pePVs); + List<PolicyEntity> peEnts = new ArrayList<PolicyEntity>(); + PolicyEntity peEnt = new PolicyEntity(); + peEnts.add(peEnt); + List<Object> peEntObjs = new ArrayList<Object>(peEnts); + Mockito.when(dao.getDataByQuery(eq("Select p from PolicyVersion p where p.policyName=:pname"), any())) + .thenReturn(peObjs); + Mockito.when( + dao.getDataByQuery(eq("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"), any())) + .thenReturn(peEntObjs); + + // Request #8 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #9 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n, \"deleteCondition\": \"All Versions\"}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + } + + @Test(expected = NullPointerException.class) + public void testDoDeletePdp() throws IOException { + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + DeleteHandler handler = new DeleteHandler(dao); + OnapLoggingContext loggingContext = new OnapLoggingContext(); + + // Mock request + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + MockHttpServletResponse response = new MockHttpServletResponse(); + + handler.doApiDeleteFromPdp(request, response, loggingContext); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java index ca6860ae8..8c35c17ef 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java @@ -2,7 +2,7 @@ * ============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 * ================================================================================ @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.handler; import static org.junit.Assert.assertNull; + import org.junit.Test; public class DictionaryHandlerTest { 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 3daed2455..ae6235f0e 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 @@ -25,13 +25,17 @@ 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.mockito.Mockito; import org.onap.policy.rest.dao.CommonClassDao; @@ -40,7 +44,6 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPPolicy; - public class PushPolicyHandlerTest { @Test public void testGetsAndChecks() { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java index e7de8d0c4..d7fbda259 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 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. @@ -22,14 +22,9 @@ package org.onap.policy.pap.xacml.rest.jpa; import static org.junit.Assert.*; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.*; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.jpa.ActionBodyEntity; -import org.onap.policy.rest.jpa.ConfigurationDataEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; -import org.onap.policy.rest.jpa.PolicyEntity; +import java.util.Date; +import java.util.List; +import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -37,560 +32,526 @@ import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; -import java.util.Date; -import java.util.List; -import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.junit.*; +import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; - -import java.util.Properties; +import org.onap.policy.rest.XacmlRestProperties; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; +import org.onap.policy.rest.jpa.PolicyEntity; public class PolicyEntityTest { private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class); @Test - public void testAllOps(){ + public void testAllOps() { Properties properties = new Properties(); - properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); - properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); - properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); - properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); + properties.put(XacmlRestProperties.PROP_PAP_DB_DRIVER, "org.h2.Driver"); + properties.put(XacmlRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); + properties.put(XacmlRestProperties.PROP_PAP_DB_USER, "sa"); + properties.put(XacmlRestProperties.PROP_PAP_DB_PASSWORD, ""); EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties); EntityManager em = emf.createEntityManager(); // Start a transaction EntityTransaction et = em.getTransaction(); et.begin(); - //Make sure the DB is clean - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + // Make sure the DB is clean + em.createQuery("DELETE FROM PolicyDbDaoEntity").executeUpdate(); em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - //Create a policy object + // Create a policy object PolicyEntity p1 = new PolicyEntity(); - - //persist the policy + + // persist the policy em.persist(p1); long policyId1 = p1.getPolicyId(); - + String policyName1 = p1.getPolicyName(); - + int version1 = p1.getVersion(); - + String policyData1 = p1.getPolicyData(); - + ConfigurationDataEntity configData1 = p1.getConfigurationData(); - String configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - + String configDataStr1 = (configData1 != null ? "configurationDataId = " + configData1.getConfigurationDataId() + : "configurationData is null"); + ActionBodyEntity actionBody1 = p1.getActionBodyEntity(); - String actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - + String actionBodyStr1 = + (actionBody1 != null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + String createdBy1 = p1.getCreatedBy(); - + Date createdDate1 = p1.getCreatedDate(); String createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - + String description = p1.getDescription(); - + String modifiedBy1 = p1.getModifiedBy(); - + Date modifiedDate1 = p1.getModifiedDate(); String modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscope = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Set policyID + + logger.debug( + "\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" + + "\npolicyId1 = " + policyId1 + "\npolicyName1 = " + policyName1 + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + "\nconfigDataStr1 = " + configDataStr1 + + "\nactionBodyStr1 = " + actionBodyStr1 + "\nscope = " + p1.getScope() + "\ncreatedBy1 = " + + createdBy1 + "\ncreatedDateStr1 = " + createdDateStr1 + "\ndescription = " + description + + "\nmodifiedBy1 = " + modifiedBy1 + "\nmodifiedDateStr1 = " + modifiedDateStr1 + "\ndeleted = " + + p1.isDeleted()); + + // Set policyID p1.setPolicyName("testPID2"); - - //Set policyData + + // Set policyData p1.setPolicyData("<policy>PolicyData</policy>"); - - //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional - - //set createdBy + + // We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional + + // set createdBy p1.setCreatedBy("kevin"); - - //createdDate will be set when it is persisted - - //set scope + + // createdDate will be set when it is persisted + + // set scope p1.setScope("mckiou.kevin"); - - //set description + + // set description p1.setDescription("PolicyEntity Description"); - - //set modifiedBy + + // set modifiedBy p1.setModifiedBy("kevin"); - - //modifiedDate will be set when it is persisted - - //Flush to the DB + + // modifiedDate will be set when it is persisted + + // Flush to the DB em.flush(); - - //Now lets get some attribute values - + + // Now lets get some attribute values + policyId1 = p1.getPolicyId(); - + policyName1 = p1.getPolicyName(); - + version1 = p1.getVersion(); - + policyData1 = p1.getPolicyData(); - + configData1 = p1.getConfigurationData(); - configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - + configDataStr1 = (configData1 != null ? "configurationDataId = " + configData1.getConfigurationDataId() + : "configurationData is null"); + actionBody1 = p1.getActionBodyEntity(); - actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - + actionBodyStr1 = + (actionBody1 != null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + createdBy1 = p1.getCreatedBy(); - + createdDate1 = p1.getCreatedDate(); createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - + description = p1.getDescription(); - + modifiedBy1 = p1.getModifiedBy(); - + modifiedDate1 = p1.getModifiedDate(); modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscopeId = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Now lets fully configure the configurationData and actionBody - - //Create a ConfigurationDataEntity object and set ID - ConfigurationDataEntity c1 = new ConfigurationDataEntity(); - - ActionBodyEntity a1 = new ActionBodyEntity(); - - //persist the configuration Data + + logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after " + + "persist*********" + + "\npolicyId1 = " + policyId1 + "\npolicyName1 = " + policyName1 + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + "\nconfigDataStr1 = " + configDataStr1 + "\nactionBodyStr1 = " + + actionBodyStr1 + "\nscopeId = " + p1.getScope() + "\ncreatedBy1 = " + createdBy1 + + "\ncreatedDateStr1 = " + createdDateStr1 + "\ndescription = " + description + "\nmodifiedBy1 = " + + modifiedBy1 + "\nmodifiedDateStr1 = " + modifiedDateStr1 + "\ndeleted = " + p1.isDeleted()); + + // Now lets fully configure the configurationData and actionBody + + // Create a ConfigurationDataEntity object and set ID + ConfigurationDataEntity c1 = new ConfigurationDataEntity(); + + ActionBodyEntity a1 = new ActionBodyEntity(); + + // persist the configuration Data em.persist(c1); - + c1.setConfigType("OTHER"); - + c1.setConfigBody("ABC"); - + c1.setDescription("ConfigurationDataEntity Description"); - + c1.setCreatedBy("kevin"); - - //c1.setModifiedBy("kevin"); - + + // c1.setModifiedBy("kevin"); + c1.setDeleted(true); - - //persist the action Body - + + // persist the action Body + em.persist(a1); - + a1.setActionBody("myActionBody"); - + a1.setActionBodyName("myActionBodyName"); - + a1.setCreatedBy("kevin"); - + a1.setModifiedBy("kevin"); - + a1.setDeleted(false); - - + long configurationDataId = c1.getConfigurationDataId(); - + int cdVersion = c1.getVersion(); - + String cdConfigType = c1.getConfigType(); - + String cdConfigBody = c1.getConfigBody(); - + String cdCreatedBy = c1.getCreatedBy(); - + Date cdCreatedDate = c1.getCreatedDate(); - + String cdDescription = c1.getDescription(); - + String cdModifiedBy = c1.getModifiedBy(); - + Date cdModifiedDate = c1.getModifiedDate(); - + logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********" - + "\nconfigurationDataId = " + configurationDataId - + "\ncdVersion = " + cdVersion - + "\ncdConfigType = " + cdConfigType - + "\ncdConfigBody = " + cdConfigBody - + "\ncdCreatedBy = " + cdCreatedBy - + "\ncdCreatedDate = " + cdCreatedDate - + "\ncdDescription = " + cdDescription - + "\ncdModifiedBy = " + cdModifiedBy - + "\ncdModifiedDate = " + cdModifiedDate - + "\ndeleted = " + c1.isDeleted()); - - - + + "\nconfigurationDataId = " + configurationDataId + "\ncdVersion = " + cdVersion + "\ncdConfigType = " + + cdConfigType + "\ncdConfigBody = " + cdConfigBody + "\ncdCreatedBy = " + cdCreatedBy + + "\ncdCreatedDate = " + cdCreatedDate + "\ncdDescription = " + cdDescription + "\ncdModifiedBy = " + + cdModifiedBy + "\ncdModifiedDate = " + cdModifiedDate + "\ndeleted = " + c1.isDeleted()); + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********" - + "\nactionBodyId = " + a1.getActionBodyId() - + "\nactionBodyVersion = " + a1.getVersion() - + "\nactionBody = " + a1.getActionBody() - + "\nactionBodyCeatedBy = " + a1.getCreatedBy() - + "\nactionBodyCreatedDate = " + a1.getCreatedDate() - + "\nactionBodyModifiedBy = " + a1.getModifiedBy() - + "\nactionBodyModifiedDate = " + a1.getModifiedDate() - + "\nactionBodyDeleted = " + a1.isDeleted()); - - p1.setScope("mckiou.kevin.kim"); - - //flush to the db + + "\nactionBodyId = " + a1.getActionBodyId() + "\nactionBodyVersion = " + a1.getVersion() + + "\nactionBody = " + a1.getActionBody() + "\nactionBodyCeatedBy = " + a1.getCreatedBy() + + "\nactionBodyCreatedDate = " + a1.getCreatedDate() + "\nactionBodyModifiedBy = " + a1.getModifiedBy() + + "\nactionBodyModifiedDate = " + a1.getModifiedDate() + "\nactionBodyDeleted = " + a1.isDeleted()); + + p1.setScope("mckiou.kevin.kim"); + + // flush to the db em.flush(); - - //Perform policy selects - + + // Perform policy selects + Query query = em.createQuery("Select p from PolicyEntity p where p.policyId=:pid"); Query queryscope = em.createQuery("Select p from PolicyEntity p where p.scope=:s"); - + query.setParameter("pid", p1.getPolicyId()); queryscope.setParameter("s", "mckiou.kevin.kim"); - - //Just test that we are retrieving the right object + + // Just test that we are retrieving the right object @SuppressWarnings("rawtypes") List psList = queryscope.getResultList(); PolicyEntity px = null; - if(!psList.isEmpty()){ - //ignores multiple results + if (!psList.isEmpty()) { + // ignores multiple results px = (PolicyEntity) psList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found"); } - - //The scope object on the retrieved policy object should be same as the one we used to find it - assertSame(p1,px); - - - //Because getSingleResult() throws an unchecked exception which is an indication of a - //programming error, we are not going to use it. + + // The scope object on the retrieved policy object should be same as the one we used to find it + assertSame(p1, px); + + // Because getSingleResult() throws an unchecked exception which is an indication of a + // programming error, we are not going to use it. @SuppressWarnings("rawtypes") List resultList = query.getResultList(); PolicyEntity p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //Confirm that the retrieved policy object is the same as the persisted object - assertSame(p1,p2); - - //Perform configurationData selects + + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning " + + "configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // Confirm that the retrieved policy object is the same as the persisted object + assertSame(p1, p2); + + // Perform configurationData selects Query query2 = em.createQuery("Select c from ConfigurationDataEntity c where c.configurationDataId=:cid"); - + query2.setParameter("cid", c1.getConfigurationDataId()); - - //Get the database version of the Configuration Data + + // Get the database version of the Configuration Data resultList = query2.getResultList(); ConfigurationDataEntity c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy2 = " + c2.getModifiedBy() - + "\nmodifiedDate2 = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //Confirm the retrieved ConfigurationDataEntity object is the same as the persisted - assertSame(c1,c2); - - //Now assign the configurationData to the policy + + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to " + + "policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy2 = " + c2.getModifiedBy() + + "\nmodifiedDate2 = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // Confirm the retrieved ConfigurationDataEntity object is the same as the persisted + assertSame(c1, c2); + + // Now assign the configurationData to the policy p1.setConfigurationData(c1); - - //Perform actionBody selects + + // Perform actionBody selects Query querya2 = em.createQuery("Select a from ActionBodyEntity a where a.actionBodyId=:aid"); - + querya2.setParameter("aid", a1.getActionBodyId()); - - //Get the database version of the Action Body + + // Get the database version of the Action Body resultList = querya2.getResultList(); ActionBodyEntity a2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results a2 = (ActionBodyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //Confirm the retrieved ActionBodyEntity object is the same as the persisted - assertSame(a1,a2); - - //Now assign the ActionBodyEntity to the policy + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to " + + "policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // Confirm the retrieved ActionBodyEntity object is the same as the persisted + assertSame(a1, a2); + + // Now assign the ActionBodyEntity to the policy p1.setActionBodyEntity(a1); em.flush(); - - //Let's retrieve the policy, configurationData and actionBody from the DB and look at them - //Here is the policy object + + // Let's retrieve the policy, configurationData and actionBody from the DB and look at them + // Here is the policy object resultList = query.getResultList(); p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("PolicyEntityTest: No PolicyEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //And now the ConfigurationDataEntity object + + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning " + + "configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // And now the ConfigurationDataEntity object resultList = query2.getResultList(); c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - - //Get the database version of the Action Body + + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to " + + "policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // Get the database version of the Action Body resultList = querya2.getResultList(); a2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results a2 = (ActionBodyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //****Now lets see if the orphanRemoval=true does anything useful*** - //Remove the configurationData from the policy relationship - + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to " + + "policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // ****Now lets see if the orphanRemoval=true does anything useful*** + // Remove the configurationData from the policy relationship + p1.setConfigurationData(null); - + p1.setActionBodyEntity(null); - - //flush the update to the DB + + // flush the update to the DB em.flush(); - - //Attempt to retrieve the configuration data object from the db. It should not be there - //Reusing the previous query + + // Attempt to retrieve the configuration data object from the db. It should not be there + // Reusing the previous query resultList = query2.getResultList(); c2 = null; - if(resultList.isEmpty()){ + if (resultList.isEmpty()) { logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + "\n Success!! No ConfigurationDataEntity DB entry found"); - - }else{ + + } else { c2 = (ConfigurationDataEntity) resultList.get(0); fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist" + "\nconfigurationDataId = " + c2.getConfigurationDataId()); } - - //Attempt to retrieve the actionBody data object from the db. It should not be there - //Reusing the previous query + + // Attempt to retrieve the actionBody data object from the db. It should not be there + // Reusing the previous query resultList = querya2.getResultList(); a2 = null; - if(resultList.isEmpty()){ + if (resultList.isEmpty()) { logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + "\n Success!! No ActionBodyEntity DB entry found"); - - }else{ + + } else { a2 = (ActionBodyEntity) resultList.get(0); - fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" - + "\nactionBodyId = " + a2.getActionBodyId()); + fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" + "\nactionBodyId = " + + a2.getActionBodyId()); } - - //Now lets put the configurationData and actionBody back into the policy object and see what appears - //in the DB after a flush - - //put c1 back into the persistence context since the orphanRemoval removed it. + + // Now lets put the configurationData and actionBody back into the policy object and see what appears + // in the DB after a flush + + // put c1 back into the persistence context since the orphanRemoval removed it. em.persist(c1); p1.setConfigurationData(c1); - + em.persist(a1); p1.setActionBodyEntity(a1); - + em.flush(); - - //retrieve the policy object + + // retrieve the policy object resultList = query.getResultList(); p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); } - - //output what we policy object found - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - - //now lets see if it put the configurationData c1 back into the table + + // output what we policy object found + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity " + + "and retrieving from DB*********" + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + + p2.getPolicyName() + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + + p2.getPolicyData() + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // now lets see if it put the configurationData c1 back into the table resultList = query2.getResultList(); c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest - Check re-entry of configurationData into DB" + "No ConfigurationDataEntity DB entry found"); } - - //output what configurationData object we found - logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //now lets see if it put the actionBody a1 back into the table - //Get the database version of the Action Body + + // output what configurationData object we found + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving " + + "from DB *********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // now lets see if it put the actionBody a1 back into the table + // Get the database version of the Action Body resultList = querya2.getResultList(); - a2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - a2 = (ActionBodyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" - + "No ActionBodyEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - //I want to save all the above in the DB - try{ + a2 = null; + if (!resultList.isEmpty()) { + // ignores multiple results + a2 = (ActionBodyEntity) resultList.get(0); + } else { + fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" + "No ActionBodyEntity DB entry found"); + } + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and " + + "retrieving from DB *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // I want to save all the above in the DB + try { et.commit(); logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } @@ -598,206 +559,184 @@ public class PolicyEntityTest { EntityTransaction et2 = em.getTransaction(); et2.begin(); - - //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold + + // Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold PolicyEntity p3 = new PolicyEntity(); em.persist(p3); - - //first let's assure that you can save with the same name but a different scope + // first let's assure that you can save with the same name but a different scope p3.setPolicyName(p1.getPolicyName()); p3.setScope("mckiou.kevin.kory"); em.flush(); logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity uniqueness constraint allowed " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope()); - - //Assert that the policyIds are NOT the same to show that the automatic sequencing is working - assert(p1.getPolicyId() != p3.getPolicyId()); - - try{ - //Now set the scope the same to verify the uniqueness constraint will be enforced + + "\nSuccess! PolicyEntity uniqueness constraint allowed " + "\n policyId1 " + p1.getPolicyId() + + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + "\n policyId3 " + + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + "\n scope3 = " + p3.getScope()); + + // Assert that the policyIds are NOT the same to show that the automatic sequencing is working + assert (p1.getPolicyId() != p3.getPolicyId()); + + try { + // Now set the scope the same to verify the uniqueness constraint will be enforced p3.setScope(p1.getScope()); em.flush(); logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope());; - } - catch(Exception e){ - //Success + + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " + "\n policyId1 " + + p1.getPolicyId() + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + + p3.getScope());; + } catch (Exception e) { + // Success logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope() - + "\n with excpetion: " + e); + + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " + "\n policyId1 " + + p1.getPolicyId() + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + + p3.getScope() + "\n with excpetion: " + e); } - - try{ + try { et2.commit(); logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } - - //****************Test the PolicyDBDaoEntity************************ - - //Create a transaction + + // ****************Test the PolicyDbDaoEntity************************ + + // Create a transaction EntityTransaction et3 = em.getTransaction(); et3.begin(); - - //create one - PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity(); + + // create one + PolicyDbDaoEntity pe1 = new PolicyDbDaoEntity(); em.persist(pe1); - + pe1.setDescription("This is pe1"); - - pe1.setPolicyDBDaoUrl("http://123.45.2.456:2345"); - - //push it to the DB + + pe1.setPolicyDbDaoUrl("http://123.45.2.456:2345"); + + // push it to the DB em.flush(); - - //create another - PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity(); + + // create another + PolicyDbDaoEntity pe2 = new PolicyDbDaoEntity(); em.persist(pe2); - + pe2.setDescription("This is pe2"); - - pe2.setPolicyDBDaoUrl("http://789.01.2.345:2345"); - - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********" - + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl() - + "\n description-1 = " + pe1.getDescription() - + "\n createdDate-1 = " + pe1.getCreatedDate() - + "\n modifiedDate-1 " + pe1.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl() - + "\n description-2 = " + pe2.getDescription() - + "\n createdDate-2 = " + pe2.getCreatedDate() - + "\n modifiedDate-2 " + pe2.getModifiedDate() - ); - - //push it to the DB + + pe2.setPolicyDbDaoUrl("http://789.01.2.345:2345"); + + // Print them to the log before flushing + logger.debug("\n\n***********PolicyEntityTest: PolicyDbDaoEntity objects before flush********" + + "\n policyDbDaoUrl-1 = " + pe1.getPolicyDbDaoUrl() + "\n description-1 = " + pe1.getDescription() + + "\n createdDate-1 = " + pe1.getCreatedDate() + "\n modifiedDate-1 " + pe1.getModifiedDate() + + "\n*****************************************" + "\n policyDbDaoUrl-2 = " + pe2.getPolicyDbDaoUrl() + + "\n description-2 = " + pe2.getDescription() + "\n createdDate-2 = " + pe2.getCreatedDate() + + "\n modifiedDate-2 " + pe2.getModifiedDate()); + + // push it to the DB em.flush(); - - //Now let's retrieve them from the DB using the named query - - resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList(); - PolicyDBDaoEntity pex = null; - PolicyDBDaoEntity pey = null; + // Now let's retrieve them from the DB using the named query + + resultList = em.createNamedQuery("PolicyDbDaoEntity.findAll").getResultList(); - if(!resultList.isEmpty()){ - if (resultList.size() != 2){ - fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2"); + PolicyDbDaoEntity pex = null; + PolicyDbDaoEntity pey = null; + + if (!resultList.isEmpty()) { + if (resultList.size() != 2) { + fail("\nPolicyEntityTest: Number of PolicyDbDaoEntity entries = " + resultList.size() + + " instead of 2"); } - for(Object policyDBDaoEntity: resultList){ - PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity; - if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ + for (Object policyDBDaoEntity : resultList) { + PolicyDbDaoEntity pdbdao = (PolicyDbDaoEntity) policyDBDaoEntity; + if (pdbdao.getPolicyDbDaoUrl().equals("http://123.45.2.456:2345")) { pex = pdbdao; - }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){ + } else if (pdbdao.getPolicyDbDaoUrl().equals("http://789.01.2.345:2345")) { pey = pdbdao; } } - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl() - + "\n description-y = " + pey.getDescription() - + "\n createdDate-y = " + pey.getCreatedDate() - + "\n modifiedDate-y " + pey.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ - assertSame(pe1,pex); - assertSame(pe2,pey); - }else{ - assertSame(pe2,pex); - assertSame(pe1,pey); + // Print them to the log before flushing + logger.debug("\n\n***********PolicyEntityTest: PolicyDbDaoEntity objects retrieved from DB********" + + "\n policyDbDaoUrl-x = " + pex.getPolicyDbDaoUrl() + "\n description-x = " + + pex.getDescription() + "\n createdDate-x = " + pex.getCreatedDate() + "\n modifiedDate-x " + + pex.getModifiedDate() + "\n*****************************************" + + "\n policyDbDaoUrl-y = " + + pey.getPolicyDbDaoUrl() + "\n description-y = " + pey.getDescription() + + "\n createdDate-y = " + + pey.getCreatedDate() + "\n modifiedDate-y " + pey.getModifiedDate()); + // Verify the retrieved objects are the same as the ones we stored in the DB + if (pex.getPolicyDbDaoUrl().equals("http://123.45.2.456:2345")) { + assertSame(pe1, pex); + assertSame(pe2, pey); + } else { + assertSame(pe2, pex); + assertSame(pe1, pey); } - - }else{ - fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found"); + + } else { + fail("\nPolicyEntityTest: No PolicyDbDaoEntity DB entry found"); } - - //Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved. - //em.persist(pex); + + // Now let's see if we can do an update on the PolicyDbDaoEntity which we retrieved. + // em.persist(pex); pex.setDescription("This is pex"); em.flush(); - - //retrieve it - Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc"); + + // retrieve it + Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDbDaoEntity p WHERE p.description=:desc"); resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList(); - PolicyDBDaoEntity pez = null; - - if(!resultList.isEmpty()){ - if (resultList.size() != 1){ - fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1"); + PolicyDbDaoEntity pez = null; + + if (!resultList.isEmpty()) { + if (resultList.size() != 1) { + fail("\nPolicyEntityTest: Update Test - Number of PolicyDbDaoEntity entries = " + resultList.size() + + " instead of 1"); } - pez = (PolicyDBDaoEntity) resultList.get(0); - - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl() - + "\n description-z = " + pez.getDescription() - + "\n createdDate-z = " + pez.getCreatedDate() - + "\n modifiedDate-z " + pez.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - assertSame(pex,pez); - }else{ - fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found"); + pez = (PolicyDbDaoEntity) resultList.get(0); + + // Print them to the log before flushing + logger.debug( + "\n\n***********PolicyEntityTest: Update Test - PolicyDbDaoEntity objects retrieved from " + + "DB********" + + "\n policyDbDaoUrl-x = " + pex.getPolicyDbDaoUrl() + "\n description-x = " + + pex.getDescription() + "\n createdDate-x = " + pex.getCreatedDate() + + "\n modifiedDate-x " + pex.getModifiedDate() + + "\n*****************************************" + "\n policyDbDaoUrl-z = " + + pez.getPolicyDbDaoUrl() + "\n description-z = " + pez.getDescription() + + "\n createdDate-z = " + pez.getCreatedDate() + "\n modifiedDate-z " + + pez.getModifiedDate()); + // Verify the retrieved objects are the same as the ones we stored in the DB + assertSame(pex, pez); + } else { + fail("\nPolicyEntityTest: Update Test - No PolicyDbDaoEntity DB updated entry found"); } - - //Clean up the DB - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + + // Clean up the DB + em.createQuery("DELETE FROM PolicyDbDaoEntity").executeUpdate(); em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - - //Wrap up the transaction - try{ + + // Wrap up the transaction + try { et3.commit(); logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } - - - //Tidy up + + // Tidy up em.close(); } - + } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java index cd6bf021d..81f9fae9d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java @@ -21,7 +21,9 @@ package org.onap.policy.pap.xacml.rest.model; import static org.junit.Assert.assertEquals; + import com.att.research.xacml.api.pap.PDPPolicy; + import org.junit.Test; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPPolicy; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java new file mode 100644 index 000000000..953fff35c --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.policycontroller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyDbDaoEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.powermock.reflect.Whitebox; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.mock.web.MockHttpServletResponse; +import com.mockrunner.mock.web.MockHttpServletRequest; + +public class PolicyCreationTest { + @Test + public void testCreation() { + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + PolicyVersion version = new PolicyVersion(); + version.setPolicyName("policyname"); + Mockito.when(dao.getEntityItem(eq(PolicyVersion.class), eq("policyName"), anyString())).thenReturn(version); + PolicyCreation.setCommonClassDao(dao); + assertEquals(dao, PolicyCreation.getCommonClassDao()); + PolicyCreation creation = new PolicyCreation(dao); + assertEquals(dao, PolicyCreation.getCommonClassDao()); + + HttpServletRequest req = new MockHttpServletRequest(); + Exception cause = new Exception("oops"); + HttpMessageNotReadableException exception = new HttpMessageNotReadableException("oops", cause); + assertEquals(HttpStatus.BAD_REQUEST, + creation.messageNotReadableExceptionHandler(req, exception).getStatusCode()); + + HttpServletResponse response = new MockHttpServletResponse(); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + policyData.setPolicyType("Config"); + policyData.setConfigPolicyType("ClosedLoop_Fault"); + policyData.setDomainDir("domain"); + policyData.setPolicyName("policyname"); + ResponseEntity<String> responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + version.setHigherVersion(1); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setEditPolicy(true); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setEditPolicy(false); + version.setHigherVersion(0); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setEditPolicy(true); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + version.setHigherVersion(1); + policyData.setConfigPolicyType("Firewall Config"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("BRMS_Raw"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("BRMS_Param"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("Base"); + Mockito.when(policyData.getRuleData()).thenReturn(new LinkedHashMap<>()); + + SessionFactory mockSessionFactory = Mockito.mock(SessionFactory.class); + Session mockSession = Mockito.mock(Session.class); + Criteria mockCriteria = Mockito.mock(Criteria.class); + List<?> policyDbDaoEntityList = new LinkedList<>(); + + Mockito.when(mockSessionFactory.openSession()).thenReturn(mockSession); + Mockito.when(mockSession.createCriteria(PolicyDbDaoEntity.class)).thenReturn(mockCriteria); + Mockito.when(mockCriteria.list()).thenReturn(policyDbDaoEntityList); + Whitebox.setInternalState(PolicyDbDao.class, "sessionfactory", mockSessionFactory); + + PolicyDbDao mockPolicyDbDao = Mockito.mock(PolicyDbDao.class); + PolicyDbDaoTransaction mockTransaction = Mockito.mock(PolicyDbDaoTransaction.class); + Mockito.when(mockPolicyDbDao.getNewTransaction()).thenReturn(mockTransaction); + + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("ClosedLoop_PM"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("Micro Service"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setConfigPolicyType("Optimization"); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setPolicyType("Action"); + List<Object> choices = new ArrayList<>(); + policyData.setRuleAlgorithmschoices(choices); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + + policyData.setPolicyType("Decision"); + List<Object> settings = new ArrayList<>(); + policyData.setSettings(settings); + responseEntity = creation.savePolicy(policyData, response); + assertThat(responseEntity).isNotNull(); + } +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java index ba400dfc0..cee67dd51 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.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. @@ -20,12 +20,18 @@ package org.onap.policy.pap.xacml.rest.service; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; +import java.io.File; +import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.FileUtils; +import org.junit.AfterClass; import org.junit.Test; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; public class ImportServiceTest { @Test @@ -34,6 +40,50 @@ public class ImportServiceTest { HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); service.doImportMicroServicePut(request, response); - assertEquals(response.getHeader("error"), "missing"); + assertEquals("missing", response.getHeader("error")); + } + + @Test + public void testImportBRMS() { + ImportService service = new ImportService(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setupAddParameter("serviceName", "serviceName"); + request.setupAddParameter("importService", "BRMSPARAM"); + request.setBodyContent("foo"); + HttpServletResponse response = new MockHttpServletResponse(); + assertThatCode(() -> service.doImportMicroServicePut(request, response)).doesNotThrowAnyException(); + } + + @Test + public void testImportMS() { + ImportService service = new ImportService(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setupAddParameter("serviceName", "serviceName"); + request.setupAddParameter("importService", "MICROSERVICE"); + request.setupAddParameter("fileName", "fileName"); + request.setBodyContent("foo"); + HttpServletResponse response = new MockHttpServletResponse(); + assertThatThrownBy(() -> service.doImportMicroServicePut(request, response)).isInstanceOf(Exception.class); + } + + @Test + public void testImportOpt() { + ImportService service = new ImportService(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setupAddParameter("serviceName", "serviceName"); + request.setupAddParameter("importService", "OPTIMIZATION"); + request.setupAddParameter("fileName", "fileName"); + request.setBodyContent("foo"); + HttpServletResponse response = new MockHttpServletResponse(); + assertThatThrownBy(() -> service.doImportMicroServicePut(request, response)).isInstanceOf(Exception.class); + } + + @AfterClass + public static void tearDown(){ + try { + FileUtils.deleteDirectory(new File("ExtractDir")); + } catch (IOException e) { + e.printStackTrace(); + } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java index c90e59bf6..8136c8329 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,27 @@ package org.onap.policy.pap.xacml.rest.service; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; + import com.mockrunner.mock.web.MockHttpServletResponse; +import java.util.ArrayList; +import java.util.List; 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.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"}) +@PrepareForTest(CommonClassDao.class) public class MetricServiceTest { @PrepareForTest({XACMLPapServlet.class}) @Test @@ -42,6 +52,19 @@ public class MetricServiceTest { MockHttpServletResponse response = new MockHttpServletResponse(); MetricService.doGetPolicyMetrics(response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode()); + } + + @Test + public void testService() { + CommonClassDao dao = Mockito.mock(CommonClassDao.class); + List<Object> value = new ArrayList<Object>(); + when(dao.getData(PolicyVersion.class)).thenReturn(value); + MetricService service = new MetricService(dao); + assertNotNull(service); + + MockHttpServletResponse response = new MockHttpServletResponse(); + MetricService.doGetPolicyMetrics(response); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode()); } } 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 ad8f86c59..6c83dcd1c 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 @@ -22,8 +22,9 @@ package org.onap.policy.pap.xacml.rest.util; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; + import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; @@ -41,7 +42,7 @@ public class JPAUtilsTest { // Test lockdown JPAUtils utils = JPAUtils.getJPAUtilsInstance(); - assertEquals(utils.dbLockdownIgnoreErrors(), false); + assertFalse(utils.dbLockdownIgnoreErrors()); utils.dbLockdown(); fail("Expecting an exception"); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java index e3a575456..fd96451f3 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.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. @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.util; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class JsonMessageTest { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java index cbe9ff250..f84f41e5f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.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,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; + import java.io.UnsupportedEncodingException; import java.util.Base64; + import org.junit.Test; import org.onap.policy.pap.xacml.restAuth.AuthenticationService; @@ -44,8 +47,7 @@ public class AuthenticationServiceTest { // Restore the original system property if (oldProperty != null) { System.setProperty(systemKey, oldProperty); - } - else { + } else { System.clearProperty(systemKey); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java index f1554e84c..c358a85ad 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP-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,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; import javax.servlet.FilterChain; @@ -34,9 +38,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; - public class PAPAuthenticationFilterTest { private HttpServletRequest request = null; @@ -47,7 +48,7 @@ public class PAPAuthenticationFilterTest { private PAPAuthenticationFilter papFilter; @Before - public void setUp(){ + public void setUp() { // Set the system property temporarily oldProperty = System.getProperty(systemKey); System.setProperty(systemKey, "xacml.pap.properties"); @@ -74,8 +75,7 @@ public class PAPAuthenticationFilterTest { try { filter.destroy(); filter.init(null); - } - catch (Exception ex) { + } catch (Exception ex) { fail("Not expecting any exceptions."); } } @@ -89,7 +89,7 @@ public class PAPAuthenticationFilterTest { callDoFilter(); } - public void callDoFilter(){ + public void callDoFilter() { try { papFilter.doFilter(request, response, filter); } catch (Exception e) { @@ -98,7 +98,7 @@ public class PAPAuthenticationFilterTest { } @Test - public void testOnPassingInvalidParamters(){ + public void testOnPassingInvalidParamters() { Mockito.when(request.getRequestURI()).thenReturn("/pap/"); Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789=="); try { @@ -110,7 +110,7 @@ public class PAPAuthenticationFilterTest { } @After - public void reset(){ + public void reset() { // Restore the original system property if (oldProperty != null) { System.setProperty(systemKey, oldProperty); |