diff options
Diffstat (limited to 'main/src/test/java')
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java | 26 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateDataTest.java | 37 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/internal/TestModels.java | 46 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/rest/depundep/ProviderSuper.java | 225 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java (renamed from main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java) | 45 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java | 214 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java | 421 | ||||
-rw-r--r-- | main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java | 258 |
8 files changed, 1161 insertions, 111 deletions
diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java index 8f064035..c36a7d4b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java @@ -42,6 +42,7 @@ import java.util.List; import java.util.Map; import java.util.Queue; import java.util.function.Consumer; +import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -56,7 +57,6 @@ import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.comm.PdpModifyRequestMap.ModifyReqData; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; @@ -133,7 +133,8 @@ public class PdpModifyRequestMapTest { response.setState(PdpState.SAFE); response.setPdpGroup(update.getPdpGroup()); response.setPdpSubgroup(update.getPdpSubgroup()); - response.setPolicies(convertToscaPolicyToToscaPolicyIndentifier()); + response.setPolicies(update.getPolicies().stream().map(ToscaPolicy::getIdentifier) + .collect(Collectors.toList())); map = new PdpModifyRequestMap(makeParameters()) { @@ -327,10 +328,13 @@ public class PdpModifyRequestMapTest { public void testModifyReqDataIsActive() { map.addRequest(update); + ModifyReqData reqdata = getReqData(PDP1); + assertNotNull(reqdata); + + // this should remove it from the map invokeProcessResponse(); - // name should have been removed - assertNull(getReqData(PDP1)); + assertFalse(reqdata.isActive()); } @Test @@ -584,18 +588,4 @@ public class PdpModifyRequestMapTest { return cng; } - - /** - * Converts a ToscaPolicy list to ToscaPolicyIdentifier list. - * - * @return the ToscaPolicyIdentifier list - */ - private List<ToscaPolicyIdentifier> convertToscaPolicyToToscaPolicyIndentifier() { - final List<ToscaPolicy> toscaPolicies = update.getPolicies(); - final List<ToscaPolicyIdentifier> toscaPolicyIdentifiers = new ArrayList<>(); - for (final ToscaPolicy toscaPolicy : toscaPolicies) { - toscaPolicyIdentifiers.add(new ToscaPolicyIdentifier(toscaPolicy.getName(), toscaPolicy.getVersion())); - } - return toscaPolicyIdentifiers; - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateDataTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateDataTest.java index 352b92df..bac85ed0 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateDataTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateDataTest.java @@ -72,7 +72,7 @@ public class UpdateDataTest { response.setName(MY_NAME); response.setPdpGroup(update.getPdpGroup()); response.setPdpSubgroup(update.getPdpSubgroup()); - response.setPolicies(convertToscaPolicyToToscaPolicyIndentifier(update.getPolicies())); + response.setPolicies(policyToIdent(update.getPolicies())); data = new MyData(update); } @@ -114,24 +114,26 @@ public class UpdateDataTest { } @Test - public void testUpdateDataCheckResponse_MismatchedPoliciesLength() { - response.setPolicies(convertToscaPolicyToToscaPolicyIndentifier(Arrays.asList(update.getPolicies().get(0)))); - - assertEquals("policies do not match", data.checkResponse(response)); - } - - @Test public void testUpdateDataCheckResponse_MismatchedPolicies() { - ArrayList<ToscaPolicyIdentifier> policies = - new ArrayList<>(convertToscaPolicyToToscaPolicyIndentifier(update.getPolicies())); - policies.set(0, new ToscaPolicyIdentifier(DIFFERENT, "10.0.0")); + ArrayList<ToscaPolicy> policies = new ArrayList<>(update.getPolicies()); + policies.set(0, makePolicy(DIFFERENT, "10.0.0")); - response.setPolicies(policies); + response.setPolicies(policyToIdent(policies)); assertEquals("policies do not match", data.checkResponse(response)); } /** + * Converts a list of policies to their corresponding identifiers. + * + * @param policies policies to be converted + * @return a list of policy identifiers + */ + private List<ToscaPolicyIdentifier> policyToIdent(List<ToscaPolicy> policies) { + return policies.stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList()); + } + + /** * Makes an update message. * * @return a new update message @@ -184,15 +186,4 @@ public class UpdateDataTest { // do nothing } } - - /** - * Converts a ToscaPolicy list to ToscaPolicyIdentifier list. - * - * @param toscaPolicies the list of ToscaPolicy - * @return the ToscaPolicyIdentifier list - */ - private List<ToscaPolicyIdentifier> convertToscaPolicyToToscaPolicyIndentifier(List<ToscaPolicy> toscaPolicies) { - return toscaPolicies.stream().map(policy -> new ToscaPolicyIdentifier(policy.getName(), policy.getVersion())) - .collect(Collectors.toList()); - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/internal/TestModels.java b/main/src/test/java/org/onap/policy/pap/main/internal/TestModels.java deleted file mode 100644 index 7cdd06ee..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/internal/TestModels.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.internal; - -import com.openpojo.reflection.filters.FilterPackageInfo; -import com.openpojo.validation.Validator; -import com.openpojo.validation.ValidatorBuilder; -import com.openpojo.validation.test.impl.GetterTester; -import com.openpojo.validation.test.impl.SetterTester; - -import org.junit.Test; -import org.onap.policy.common.utils.validation.ToStringTester; - -/** - * Class to perform unit testing of models. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestModels { - - @Test - public void testPapModels() { - final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterTester()) - .with(new GetterTester()).build(); - validator.validate(TestModels.class.getPackage().getName(), new FilterPackageInfo()); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/ProviderSuper.java new file mode 100644 index 00000000..3a3673d5 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/ProviderSuper.java @@ -0,0 +1,225 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * 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.main.rest.depundep; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.pap.main.PapConstants; +import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.comm.PdpModifyRequestMap; + +/** + * Super class for TestPdpGroupDeployProviderXxx classes. + */ +public class ProviderSuper { + private static final Coder coder = new StandardCoder(); + + @Mock + protected PolicyModelsProvider dao; + + /** + * Used to capture input to dao.createPdpGroups(). + */ + @Captor + private ArgumentCaptor<List<PdpGroup>> createCaptor; + + + /** + * Used to capture input to dao.updatePdpGroups(). + */ + @Captor + private ArgumentCaptor<List<PdpGroup>> updateCaptor; + + protected Object lockit; + protected PdpModifyRequestMap reqmap; + protected PolicyModelsProviderFactoryWrapper daofact; + protected ToscaPolicy policy1; + + + /** + * Configures DAO, captors, and various mocks. + */ + @Before + public void setUp() throws Exception { + + Registry.newRegistry(); + + MockitoAnnotations.initMocks(this); + + reqmap = mock(PdpModifyRequestMap.class); + + lockit = new Object(); + daofact = mock(PolicyModelsProviderFactoryWrapper.class); + policy1 = loadFile("policy.json", ToscaPolicy.class); + + when(daofact.create()).thenReturn(dao); + + List<PdpGroup> groups = loadGroups("groups.json"); + + when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + + when(dao.createPdpGroups(any())).thenAnswer(answer -> answer.getArgumentAt(0, List.class)); + when(dao.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgumentAt(0, List.class)); + + Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, lockit); + Registry.register(PapConstants.REG_PDP_MODIFY_MAP, reqmap); + Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); + } + + protected void assertGroup(List<PdpGroup> groups, String name, String version) { + PdpGroup group = groups.remove(0); + + assertEquals(name, group.getName()); + assertEquals(version, group.getVersion()); + } + + protected void assertUpdateIgnorePolicy(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) { + + PdpUpdate update = updates.remove(0); + + assertEquals(groupName, update.getPdpGroup()); + assertEquals(pdpType, update.getPdpSubgroup()); + assertEquals(pdpName, update.getName()); + } + + /** + * Gets the input to the method. + * + * @param count the number of times the method is expected to have been called. + * @return the input that was passed to the dao.createPdpGroups() method + * @throws Exception if an error occurred + */ + protected List<List<PdpGroup>> getGroupCreates(int count) throws Exception { + verify(dao, times(count)).createPdpGroups(createCaptor.capture()); + + return copyLists(createCaptor.getAllValues()); + } + + /** + * Gets the input to the method. + * + * @param count the number of times the method is expected to have been called + * @return the input that was passed to the dao.updatePdpGroups() method + * @throws Exception if an error occurred + */ + protected List<List<PdpGroup>> getGroupUpdates(int count) throws Exception { + verify(dao, times(count)).updatePdpGroups(updateCaptor.capture()); + + return copyLists(updateCaptor.getAllValues()); + } + + /** + * Gets the updates that were added to the request map. + * + * @param count the number of times the method is expected to have been called + * @return the updates that were added to the request map + */ + protected List<PdpUpdate> getUpdateRequests(int count) { + ArgumentCaptor<PdpUpdate> captor = ArgumentCaptor.forClass(PdpUpdate.class); + + verify(reqmap, times(count)).addRequest(captor.capture()); + + return new ArrayList<>(captor.getAllValues()); + } + + /** + * Makes a partly deep copy of the list. + * + * @param source source list to copy + * @return a copy of the source list + */ + private List<List<PdpGroup>> copyLists(List<List<PdpGroup>> source) { + List<List<PdpGroup>> target = new ArrayList<>(source.size()); + + for (List<PdpGroup> lst : source) { + target.add(new ArrayList<>(lst)); + } + + return target; + } + + /** + * Loads a list of groups. + * + * @param fileName name of the file from which to load + * @return a list of groups + */ + protected List<PdpGroup> loadGroups(String fileName) { + return loadFile(fileName, org.onap.policy.models.pdp.concepts.PdpGroups.class).getGroups(); + } + + /** + * Loads a list of policies. + * + * @param fileName name of the file from which to load + * @return a list of policies + */ + protected List<ToscaPolicy> loadPolicies(String fileName) { + return loadFile(fileName, PolicyList.class).policies; + } + + /** + * Loads an object from a JSON file. + * + * @param fileName name of the file from which to load + * @param clazz the class of the object to be loaded + * @return the object that was loaded from the file + */ + protected <T> T loadFile(String fileName, Class<T> clazz) { + File propFile = new File(ResourceUtils.getFilePath4Resource("simpleDeploy/" + fileName)); + try { + return coder.decode(propFile, clazz); + + } catch (CoderException e) { + throw new RuntimeException(e); + } + } + + /** + * Wraps a list of policies. The decoder doesn't work with generic lists, so we wrap + * the list and decode it into the wrapper before extracting the list contents. + */ + private static class PolicyList { + private List<ToscaPolicy> policies; + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java index 09e91a99..73a4f0e5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployControllerV1.java @@ -1,4 +1,4 @@ -/*- +/* * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. @@ -19,10 +19,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.main.rest; +package org.onap.policy.pap.main.rest.depundep; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertNotNull; import java.util.Arrays; import javax.ws.rs.client.Entity; @@ -35,6 +35,7 @@ import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; +import org.onap.policy.pap.main.rest.CommonPapRestServer; public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { @@ -49,18 +50,18 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { @Test public void testDeployGroup() throws Exception { - final Entity<PdpGroup> entgrp = makePdpGroupEntity(); + Entity<PdpGroup> entgrp = makePdpGroupEntity(); - final Invocation.Builder invocationBuilder = sendRequest(DEPLOY_GROUP_ENDPOINT); + Invocation.Builder invocationBuilder = sendRequest(DEPLOY_GROUP_ENDPOINT); Response rawresp = invocationBuilder.post(entgrp); PdpGroupDeployResponse resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); - assertNull(resp.getErrorDetails()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertNotNull(resp.getErrorDetails()); rawresp = invocationBuilder.post(entgrp); resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); - assertNull(resp.getErrorDetails()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertNotNull(resp.getErrorDetails()); // verify it fails when no authorization info is included checkUnauthRequest(DEPLOY_GROUP_ENDPOINT, req -> req.post(entgrp)); @@ -68,28 +69,28 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { @Test public void testDeployPolicies() throws Exception { - final Entity<PdpDeployPolicies> entgrp = makePdpPoliciesEntity(); + Entity<PdpDeployPolicies> entgrp = makePdpPoliciesEntity(); - final Invocation.Builder invocationBuilder = sendRequest(DEPLOY_POLICIES_ENDPOINT); + Invocation.Builder invocationBuilder = sendRequest(DEPLOY_POLICIES_ENDPOINT); Response rawresp = invocationBuilder.post(entgrp); PdpGroupDeployResponse resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); - assertNull(resp.getErrorDetails()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertNotNull(resp.getErrorDetails()); rawresp = invocationBuilder.post(entgrp); resp = rawresp.readEntity(PdpGroupDeployResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); - assertNull(resp.getErrorDetails()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rawresp.getStatus()); + assertNotNull(resp.getErrorDetails()); // verify it fails when no authorization info is included checkUnauthRequest(DEPLOY_POLICIES_ENDPOINT, req -> req.post(entgrp)); } private Entity<PdpGroup> makePdpGroupEntity() { - final PdpSubGroup subgrp = new PdpSubGroup(); + PdpSubGroup subgrp = new PdpSubGroup(); subgrp.setPdpType("drools"); - final PdpGroup group = new PdpGroup(); + PdpGroup group = new PdpGroup(); group.setName("drools-group"); group.setDescription("my description"); group.setVersion("my-version"); @@ -99,14 +100,10 @@ public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { } private Entity<PdpDeployPolicies> makePdpPoliciesEntity() { - final ToscaPolicyIdentifierOptVersion pol1 = new ToscaPolicyIdentifierOptVersion(); - pol1.setName("policy-a"); - pol1.setVersion("1"); + ToscaPolicyIdentifierOptVersion pol1 = new ToscaPolicyIdentifierOptVersion("policy-a", "1"); + ToscaPolicyIdentifierOptVersion pol2 = new ToscaPolicyIdentifierOptVersion("policy-b", null); - final ToscaPolicyIdentifierOptVersion pol2 = new ToscaPolicyIdentifierOptVersion(); - pol2.setName("policy-b"); - - final PdpDeployPolicies policies = new PdpDeployPolicies(); + PdpDeployPolicies policies = new PdpDeployPolicies(); policies.setPolicies(Arrays.asList(pol1, pol2)); return Entity.entity(policies, MediaType.APPLICATION_JSON); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java new file mode 100644 index 00000000..d3ffda84 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestPdpGroupDeployProvider.java @@ -0,0 +1,214 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * 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.main.rest.depundep; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.policy.pap.main.rest.depundep.ProviderBase.DB_ERROR_MSG; + +import java.util.List; +import javax.ws.rs.core.Response.Status; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.pap.concepts.PdpDeployPolicies; +import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; +import org.onap.policy.models.pdp.concepts.PdpGroups; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.pap.main.rest.depundep.PdpGroupDeployProvider; + +public class TestPdpGroupDeployProvider extends ProviderSuper { + private static final String EXPECTED_EXCEPTION = "expected exception"; + private static final Object REQUEST_FAILED_MSG = "request failed"; + + private static final String POLICY1_NAME = "policyA"; + private static final String POLICY1_VERSION = "1.2.3"; + private static final String GROUP1_NAME = "groupA"; + private static final String GROUP1_VERSION = "200.2.3"; + private static final String GROUP1_NEW_VERSION = "201.0.0"; + private static final String PDP1_TYPE = "pdpTypeA"; + private static final String PDP2_TYPE = "pdpTypeB"; + private static final String PDP4_TYPE = "pdpTypeD"; + private static final String PDP2 = "pdpB"; + private static final String PDP4 = "pdpD"; + + private PdpGroupDeployProvider prov; + + + @AfterClass + public static void tearDownAfterClass() { + Registry.newRegistry(); + } + + /** + * Configures mocks and objects. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + + super.setUp(); + + when(dao.getPolicyList(POLICY1_NAME, POLICY1_VERSION)).thenReturn(loadPolicies("daoPolicyList.json")); + + prov = new PdpGroupDeployProvider(); + } + + @Test + public void testDeployGroup() { + Pair<Status, PdpGroupDeployResponse> pair = prov.deployGroup(new PdpGroups()); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals("not implemented yet", pair.getRight().getErrorDetails()); + } + + @Test + public void testDeployPolicies() { + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadEmptyRequest()); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + } + + @Test + public void testDeploySimplePolicies() throws Exception { + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + } + + @Test + public void testDeploySimplePolicies_DaoEx() throws Exception { + when(dao.getFilteredPdpGroups(any())).thenThrow(new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION)); + + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals(DB_ERROR_MSG, pair.getRight().getErrorDetails()); + } + + @Test + public void testDeploySimplePolicies_RuntimeEx() throws Exception { + when(dao.getPolicyList(any(), any())).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals(REQUEST_FAILED_MSG, pair.getRight().getErrorDetails()); + } + + @Test + public void testDeploySimplePolicies_NoGroups() throws Exception { + when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); + + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals("policy not supported by any PDP group: policyA 1.2.3", pair.getRight().getErrorDetails()); + } + + @Test + public void testMakeUpdater() throws Exception { + /* + * Each subgroup has a different PDP type and name. + * + * Type is not supported by the first subgroup. + * + * Second subgroup matches. + * + * Third subgroup already contains the policy. + * + * Last subgroup matches. + */ + + when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + assertGroup(getGroupUpdates(1).get(0), GROUP1_NAME, GROUP1_VERSION); + assertGroup(getGroupCreates(1).get(0), GROUP1_NAME, GROUP1_NEW_VERSION); + + List<PdpUpdate> requests = getUpdateRequests(2); + assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2); + assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4); + } + + @Test + public void testMakeUpdater_NoPdps() throws Exception { + + // subgroup has no PDPs + when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); + + Pair<Status, PdpGroupDeployResponse> pair = prov.deployPolicies(loadRequest()); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs", + pair.getRight().getErrorDetails()); + + verify(dao, never()).createPdpGroups(any()); + verify(dao, never()).updatePdpGroups(any()); + verify(reqmap, never()).addRequest(any(PdpUpdate.class)); + } + + + protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) { + + PdpUpdate update = updates.remove(0); + + assertEquals(groupName, update.getPdpGroup()); + assertEquals(pdpType, update.getPdpSubgroup()); + assertEquals(pdpName, update.getName()); + assertTrue(update.getPolicies().contains(policy1)); + } + + /** + * Loads a standard request. + * + * @return a standard request + */ + protected PdpDeployPolicies loadRequest() { + return loadRequest("request.json"); + } + + /** + * Loads a request from a JSON file. + * + * @param fileName name of the file from which to load + * @return the request that was loaded + */ + protected PdpDeployPolicies loadRequest(String fileName) { + return loadFile(fileName, PdpDeployPolicies.class); + } + + /** + * Loads an empty request. + * + * @return an empty request + */ + protected PdpDeployPolicies loadEmptyRequest() { + return loadRequest("emptyRequest.json"); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java new file mode 100644 index 00000000..f64f77da --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestProviderBase.java @@ -0,0 +1,421 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * 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.main.rest.depundep; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.policy.pap.main.rest.depundep.ProviderBase.DB_ERROR_MSG; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.function.BiFunction; +import javax.ws.rs.core.Response.Status; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.pap.concepts.PdpDeployPolicies; +import org.onap.policy.models.pap.concepts.SimpleResponse; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion; +import org.onap.policy.pap.main.PolicyPapRuntimeException; +import org.powermock.reflect.Whitebox; + +public class TestProviderBase extends ProviderSuper { + private static final String EXPECTED_EXCEPTION = "expected exception"; + private static final Object REQUEST_FAILED_MSG = "request failed"; + + private static final String POLICY1_NAME = "policyA"; + private static final String POLICY1_VERSION = "1.2.3"; + private static final String GROUP1_NAME = "groupA"; + private static final String GROUP1_VERSION = "200.2.3"; + private static final String GROUP1_NEW_VERSION = "201.0.0"; + private static final String GROUP2_NAME = "groupB"; + private static final String PDP1_TYPE = "pdpTypeA"; + private static final String PDP2_TYPE = "pdpTypeB"; + private static final String PDP3_TYPE = "pdpTypeC"; + private static final String PDP4_TYPE = "pdpTypeD"; + private static final String PDP1 = "pdpA"; + private static final String PDP2 = "pdpB"; + private static final String PDP3 = "pdpC"; + private static final String PDP4 = "pdpD"; + + private MyProvider prov; + + + @AfterClass + public static void tearDownAfterClass() { + Registry.newRegistry(); + } + + /** + * Configures mocks and objects. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + + super.setUp(); + + when(dao.getPolicyList(POLICY1_NAME, POLICY1_VERSION)).thenReturn(loadPolicies("daoPolicyList.json")); + + prov = new MyProvider(); + } + + @Test + public void testProviderBase() { + assertSame(lockit, Whitebox.getInternalState(prov, "updateLock")); + assertSame(reqmap, Whitebox.getInternalState(prov, "requestMap")); + assertSame(daofact, Whitebox.getInternalState(prov, "daoFactory")); + } + + @Test + public void testProcess() throws Exception { + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + assertGroup(getGroupUpdates(1).get(0), GROUP1_NAME, GROUP1_VERSION); + assertGroup(getGroupCreates(1).get(0), GROUP1_NAME, GROUP1_NEW_VERSION); + + assertUpdate(getUpdateRequests(1), GROUP1_NAME, PDP1_TYPE, PDP1); + } + + @Test + public void testProcess_CreateEx() throws Exception { + when(daofact.create()).thenThrow(new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION)); + + Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals(DB_ERROR_MSG, pair.getRight().getErrorDetails()); + } + + @Test + public void testProcess_PapEx() throws Exception { + when(daofact.create()).thenThrow(new PolicyPapRuntimeException(EXPECTED_EXCEPTION)); + + Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals(EXPECTED_EXCEPTION, pair.getRight().getErrorDetails()); + } + + @Test + public void testProcess_RuntimeEx() throws Exception { + when(daofact.create()).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + + Pair<Status, MyResponse> pair = prov.process(loadEmptyRequest(), this::handle); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals(REQUEST_FAILED_MSG, pair.getRight().getErrorDetails()); + } + + @Test + public void testProcessPolicy_NoGroups() throws Exception { + when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); + + SessionData session = new SessionData(dao); + ToscaPolicyIdentifierOptVersion ident = new ToscaPolicyIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION); + assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PolicyPapRuntimeException.class) + .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); + + } + + @Test + public void testGetPolicy() throws Exception { + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + verify(dao).getPolicyList(any(), any()); + verify(dao, never()).getFilteredPolicyList(any()); + } + + @Test + public void testGetPolicy_NullVersion() throws Exception { + // only allow this query once + when(dao.getPolicyList(POLICY1_NAME, POLICY1_VERSION)).thenReturn(loadPolicies("daoPolicyList.json")) + .thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + + when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + + Pair<Status, MyResponse> pair = prov.process(loadRequest("getPolicyReqNullVersion.json"), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + verify(dao).getFilteredPolicyList(any()); + verify(dao, never()).getPolicies(any(), any()); + } + + @Test + public void testGetPolicy_NotFound() throws Exception { + when(dao.getPolicyList(any(), any())).thenReturn(Collections.emptyList()); + + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.INTERNAL_SERVER_ERROR, pair.getLeft()); + assertEquals("cannot find policy: " + POLICY1_NAME + " " + POLICY1_VERSION, pair.getRight().getErrorDetails()); + } + + @Test + public void testGetGroup() throws Exception { + when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) + .thenReturn(loadGroups("groups.json")); + + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + assertGroup(getGroupUpdates(1).get(0), GROUP1_NAME, GROUP1_VERSION); + assertGroup(getGroupCreates(1).get(0), GROUP1_NAME, GROUP1_NEW_VERSION); + } + + @Test + public void testUpgradeGroup() throws Exception { + /* + * Each subgroup has a different PDP type and name. + * + * Type is not supported by the first subgroup. + * + * Second subgroup matches. + * + * Third subgroup already contains the policy. + * + * Last subgroup matches. + */ + + when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + + prov.clear(); + prov.add(false, true, false, true); + + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + assertGroup(getGroupUpdates(1).get(0), GROUP1_NAME, GROUP1_VERSION); + assertGroup(getGroupCreates(1).get(0), GROUP1_NAME, GROUP1_NEW_VERSION); + + List<PdpUpdate> requests = getUpdateRequests(2); + assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2); + assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4); + } + + @Test + public void testUpgradeGroup_Multiple() throws Exception { + /* + * Policy data in the DB: policy1=type1, policy2=type2, policy3=type3, + * policy4=type1 + * + * Group data in the DB: group1=(type1=pdp1, type3=pdp3) group2=(type2=pdp2) + * + * Request specifies: policy1, policy2, policy3, policy4 + * + * Should create new versions of group1 and group2. + * + * Should update old versions of group1 and group2. Should also update new version + * of group1 twice. + * + * Should generate updates to pdp1, pdp2, and pdp3. + */ + + when(dao.getPolicyList(POLICY1_NAME, POLICY1_VERSION)).thenReturn(loadPolicies("daoPolicyList.json")); + when(dao.getPolicyList("policyB", POLICY1_VERSION)).thenReturn(loadPolicies("upgradeGroupPolicy2.json")); + when(dao.getPolicyList("policyC", POLICY1_VERSION)).thenReturn(loadPolicies("upgradeGroupPolicy3.json")); + when(dao.getPolicyList("policyD", POLICY1_VERSION)).thenReturn(loadPolicies("upgradeGroupPolicy4.json")); + + List<PdpGroup> groups1 = loadGroups("upgradeGroupGroup1.json"); + List<PdpGroup> groups2 = loadGroups("upgradeGroupGroup2.json"); + + /* + * these are in pairs of (get-group, get-max-group) matching each policy in the + * request + */ + // @formatter:off + when(dao.getFilteredPdpGroups(any())) + .thenReturn(groups1).thenReturn(groups1) + .thenReturn(groups2).thenReturn(groups2) + .thenReturn(groups1).thenReturn(groups1) + .thenReturn(groups1).thenReturn(groups1); + // @formatter:on + + // multiple policies in the request + PdpDeployPolicies request = loadFile("updateGroupReqMultiple.json", PdpDeployPolicies.class); + + Pair<Status, MyResponse> pair = prov.process(request, (data, deploy) -> { + for (ToscaPolicyIdentifierOptVersion policy : deploy.getPolicies()) { + handle(data, policy); + } + }); + + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + List<List<PdpGroup>> creates = getGroupCreates(2); + assertGroup(creates.get(0), GROUP1_NAME, GROUP1_NEW_VERSION); + assertGroup(creates.get(1), GROUP2_NAME, "301.0.0"); + + List<List<PdpGroup>> updates = getGroupUpdates(4); + assertGroup(updates.get(0), GROUP1_NAME, GROUP1_VERSION); + assertGroup(updates.get(1), GROUP2_NAME, "300.2.3"); + assertGroup(updates.get(2), GROUP1_NAME, GROUP1_NEW_VERSION); + assertGroup(updates.get(3), GROUP1_NAME, GROUP1_NEW_VERSION); + + List<PdpUpdate> requests = getUpdateRequests(3); + assertUpdateIgnorePolicy(requests, GROUP1_NAME, PDP1_TYPE, PDP1); + assertUpdateIgnorePolicy(requests, GROUP2_NAME, PDP2_TYPE, PDP2); + assertUpdateIgnorePolicy(requests, GROUP1_NAME, PDP3_TYPE, PDP3); + } + + @Test + public void testUpgradeGroup_NothingUpdated() throws Exception { + prov.clear(); + prov.add(false); + + Pair<Status, MyResponse> pair = prov.process(loadRequest(), this::handle); + assertEquals(Status.OK, pair.getLeft()); + assertNull(pair.getRight().getErrorDetails()); + + verify(dao, never()).createPdpGroups(any()); + verify(dao, never()).updatePdpGroups(any()); + verify(reqmap, never()).addRequest(any(PdpUpdate.class)); + } + + + protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) { + + PdpUpdate update = updates.remove(0); + + assertEquals(groupName, update.getPdpGroup()); + assertEquals(pdpType, update.getPdpSubgroup()); + assertEquals(pdpName, update.getName()); + assertTrue(update.getPolicies().contains(policy1)); + } + + /** + * Loads a standard request. + * + * @return a standard request + */ + protected ToscaPolicyIdentifierOptVersion loadRequest() { + return loadRequest("requestBase.json"); + } + + /** + * Loads a request from a JSON file. + * + * @param fileName name of the file from which to load + * @return the request that was loaded + */ + protected ToscaPolicyIdentifierOptVersion loadRequest(String fileName) { + return loadFile(fileName, ToscaPolicyIdentifierOptVersion.class); + } + + /** + * Loads an empty request. + * + * @return an empty request + */ + protected ToscaPolicyIdentifierOptVersion loadEmptyRequest() { + return loadRequest("emptyRequestBase.json"); + } + + /** + * Handles a request by invoking the provider's processPolicy method. + * + * @param data session data + * @param request request to be handled + */ + private void handle(SessionData data, ToscaPolicyIdentifierOptVersion request) { + try { + prov.processPolicy(data, request); + + } catch (PfModelException e) { + throw new PolicyPapRuntimeException(e); + } + } + + + private static class MyProvider extends ProviderBase<MyResponse> { + /** + * Used to determine whether or not to make an update when + * {@link #makeUpdater(ToscaPolicy)} is called. The updater function removes an + * item from this queue each time it is invoked. + */ + private final Queue<Boolean> shouldUpdate = new LinkedList<>(); + + /** + * Constructs the object and queues up several successful updates. + */ + public MyProvider() { + for (int x = 0; x < 10; ++x) { + shouldUpdate.add(true); + } + } + + public void clear() { + shouldUpdate.clear(); + } + + public void add(Boolean... update) { + shouldUpdate.addAll(Arrays.asList(update)); + } + + @Override + public MyResponse makeResponse(String errorMsg) { + return new MyResponse(errorMsg); + } + + @Override + protected BiFunction<PdpGroup, PdpSubGroup, Boolean> makeUpdater(ToscaPolicy policy) { + return (group, subgroup) -> { + if (shouldUpdate.remove()) { + // queue indicated that the update should succeed + subgroup.getPolicies().add(policy.getIdentifier()); + return true; + + } else { + // queue indicated that no update should be made this time + return false; + } + }; + } + } + + private static class MyResponse extends SimpleResponse { + public MyResponse(String errorMsg) { + setErrorDetails(errorMsg); + } + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java new file mode 100644 index 00000000..6be5c8ac --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/depundep/TestSessionData.java @@ -0,0 +1,258 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * 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.main.rest.depundep; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; +import org.onap.policy.pap.main.PolicyPapRuntimeException; + +public class TestSessionData extends ProviderSuper { + private static final String GROUP_VERSION_PREFIX = "9.8."; + private static final String GROUP_NAME = "group"; + private static final String GROUP_VERSION = GROUP_VERSION_PREFIX + "7"; + private static final String GROUP_NAME2 = "group2"; + private static final String GROUP_VERSION2 = GROUP_VERSION_PREFIX + "6"; + private static final String PDP1 = "pdp_1"; + private static final String PDP2 = "pdp_2"; + private static final String PDP3 = "pdp_3"; + private static final String POLICY_VERSION_PREFIX = "1.2."; + private static final String POLICY_NAME = "myPolicy"; + private static final String POLICY_VERSION = POLICY_VERSION_PREFIX + "3"; + private static final String POLICY_VERSION2 = POLICY_VERSION_PREFIX + "4"; + + private SessionData session; + private ToscaPolicyIdentifier ident; + + /** + * Initializes mocks and a session. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + super.setUp(); + + ident = new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION); + + session = new SessionData(dao); + } + + @Test + public void testGetPolicy() throws Exception { + ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); + when(dao.getPolicyList(POLICY_NAME, POLICY_VERSION)).thenReturn(Arrays.asList(policy1)); + + ToscaPolicy policy2 = makePolicy(POLICY_NAME, POLICY_VERSION2); + when(dao.getPolicyList(POLICY_NAME, POLICY_VERSION2)).thenReturn(Arrays.asList(policy2)); + + ToscaPolicyIdentifier ident2 = new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION2); + + assertSame(policy1, session.getPolicy(ident)); + assertSame(policy2, session.getPolicy(ident2)); + + // repeat + assertSame(policy1, session.getPolicy(ident)); + assertSame(policy2, session.getPolicy(ident2)); + + assertSame(policy1, session.getPolicy(ident)); + assertSame(policy2, session.getPolicy(ident2)); + + // should have only invoked this once for each policy + verify(dao, times(2)).getPolicyList(any(), any()); + } + + @Test + public void testGetPolicy_NotFound() throws Exception { + when(dao.getPolicyList(any(), any())).thenReturn(Collections.emptyList()); + + assertThatThrownBy(() -> session.getPolicy(ident)).hasMessage("cannot find policy: myPolicy 1.2.3"); + } + + @Test + public void testGetPolicy_TooMany() throws Exception { + ToscaPolicy policy = new ToscaPolicy(); + when(dao.getPolicyList(any(), any())).thenReturn(Arrays.asList(policy, policy)); + + assertThatThrownBy(() -> session.getPolicy(ident)).hasMessage("too many policies match: myPolicy 1.2.3"); + } + + @Test + public void testGetPolicy_DaoEx() throws Exception { + PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, "expected exception"); + when(dao.getPolicyList(any(), any())).thenThrow(ex); + + assertThatThrownBy(() -> session.getPolicy(ident)).hasMessage("cannot get policy: myPolicy 1.2.3").hasCause(ex); + } + + @Test + public void testAddUpdate() { + // several different updates, but one duplicate + PdpUpdate update1 = makeUpdate(PDP1); + session.addUpdate(update1); + + PdpUpdate update2 = makeUpdate(PDP2); + session.addUpdate(update2); + + PdpUpdate update3 = makeUpdate(PDP3); + session.addUpdate(update3); + + List<PdpUpdate> lst = sort(session.getUpdates(), this::compare); + assertEquals(Arrays.asList(update1, update2, update3).toString(), lst.toString()); + + // overwrite one + update2 = makeUpdate(PDP2); + session.addUpdate(update2); + + lst = sort(session.getUpdates(), this::compare); + assertEquals(Arrays.asList(update1, update2, update3).toString(), lst.toString()); + } + + private ToscaPolicy makePolicy(String name, String version) { + ToscaPolicy policy = new ToscaPolicy(); + + policy.setName(name); + policy.setVersion(version); + + return policy; + } + + @Test + public void testGetPolicyMaxVersion() throws Exception { + ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); + + when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + + assertSame(policy1, session.getPolicyMaxVersion(POLICY_NAME)); + + // no matching policies - should throw an exception + when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + assertThatThrownBy(() -> session.getPolicyMaxVersion(POLICY_NAME)).hasMessage("cannot find policy: myPolicy"); + } + + @Test + public void testIsNewlyCreated_testCreatePdpGroup() throws Exception { + assertFalse(session.isNewlyCreated(GROUP_NAME)); + + PdpGroup group1 = makeGroup(GROUP_NAME, GROUP_VERSION); + when(dao.createPdpGroups(any())).thenReturn(Arrays.asList(group1)); + + session.createPdpGroup(group1); + + assertTrue(session.isNewlyCreated(GROUP_NAME)); + assertFalse(session.isNewlyCreated(GROUP_NAME2)); + + PdpGroup group2 = makeGroup(GROUP_NAME2, GROUP_VERSION2); + when(dao.createPdpGroups(any())).thenReturn(Arrays.asList(group2)); + session.createPdpGroup(group2); + + List<List<PdpGroup>> creates = getGroupCreates(2); + assertEquals(group1, creates.get(0).get(0)); + assertEquals(group2, creates.get(1).get(0)); + + assertTrue(session.isNewlyCreated(GROUP_NAME)); + assertTrue(session.isNewlyCreated(GROUP_NAME2)); + } + + private PdpGroup makeGroup(String name, String version) { + PdpGroup group = new PdpGroup(); + + group.setName(name); + group.setVersion(version); + + return group; + } + + @Test + public void testGetPdpGroupMaxVersion() throws Exception { + PdpGroup group = makeGroup(GROUP_NAME, GROUP_VERSION); + when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); + + assertEquals(group, session.getPdpGroupMaxVersion(GROUP_NAME)); + + // try empty list + when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); + assertThatThrownBy(() -> session.getPdpGroupMaxVersion(GROUP_NAME)) + .isInstanceOf(PolicyPapRuntimeException.class).hasMessage("cannot find group: group"); + } + + @Test + public void testGetActivePdpGroupsByPolicyType() throws Exception { + List<PdpGroup> groups = + Arrays.asList(makeGroup(GROUP_NAME, GROUP_VERSION), makeGroup(GROUP_NAME2, GROUP_VERSION2)); + when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + + assertEquals(groups, session + .getActivePdpGroupsByPolicyType(new ToscaPolicyTypeIdentifier(POLICY_NAME, POLICY_VERSION))); + } + + @Test + public void testUpdatePdpGroup() throws Exception { + PdpGroup group = makeGroup(GROUP_NAME, GROUP_VERSION); + when(dao.updatePdpGroups(any())).thenReturn(Arrays.asList(group)); + + session.updatePdpGroup(group); + + List<PdpGroup> updates = getGroupUpdates(1).get(0); + assertEquals(group, updates.get(0)); + } + + private PdpUpdate makeUpdate(String pdpName) { + PdpUpdate update = new PdpUpdate(); + + update.setName(pdpName); + + return update; + } + + private <T> List<T> sort(Collection<T> collection, Comparator<T> comparator) { + List<T> lst = new ArrayList<>(collection); + Collections.sort(lst, comparator); + + return lst; + } + + private int compare(PdpUpdate left, PdpUpdate right) { + return left.getName().compareTo(right.getName()); + } +} |