diff options
author | a.sreekumar <ajith.sreekumar@bell.ca> | 2022-02-07 16:05:17 +0000 |
---|---|---|
committer | a.sreekumar <ajith.sreekumar@bell.ca> | 2022-02-10 10:31:15 +0000 |
commit | 873803eca00830dc3ecb61e610d90710f64a8242 (patch) | |
tree | 31531d76a87c300577da83bdf86563b78a015fce /main/src/test/java | |
parent | ed116b0d61f3195a1b0ed9d38f23e494260977fd (diff) |
Move PAP database provider to spring boot default
This review makes PAP talk to DB directly using the spring repositories
instead of going to policy-models-provider.
The models-provider methods that were just used by PAP (and not used
anymore) will be removed in a different review.
Also a bug identified with the usage of GeneratedValue in
PfGeneratedIdKey (which is just used by PAP in statistics & audit) will
also be fixed in a separate review as part of POLICY-3897.
CSIT changes: https://gerrit.onap.org/r/c/policy/docker/+/127033
WIP OOM review: https://gerrit.onap.org/r/c/oom/+/127035
Change-Id: Idb13ba7eb2767cc718672b582a6518fcfc95320f
Issue-ID: POLICY-3867
Signed-off-by: a.sreekumar <ajith.sreekumar@bell.ca>
Diffstat (limited to 'main/src/test/java')
31 files changed, 1000 insertions, 1155 deletions
diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java index 0dc6636b..dd206062 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -43,10 +44,8 @@ import org.onap.policy.models.pdp.concepts.PdpStateChange; 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.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.msgdata.RequestListener; import org.onap.policy.pap.main.comm.msgdata.StateChangeReq; import org.onap.policy.pap.main.comm.msgdata.UpdateReq; @@ -84,8 +83,6 @@ public class CommonRequestBase { protected TimerManager.Timer timer; protected Queue<QueueToken<PdpMessage>> queue; protected RequestListener listener; - protected PolicyModelsProviderFactoryWrapper daoFactory; - protected PolicyModelsProvider dao; protected RequestParams reqParams; protected PdpModifyRequestMapParams mapParams; @@ -105,9 +102,6 @@ public class CommonRequestBase { timer = mock(TimerManager.Timer.class); queue = new LinkedList<>(); listener = mock(RequestListener.class); - daoFactory = mock(PolicyModelsProviderFactoryWrapper.class); - dao = mock(PolicyModelsProvider.class); - PdpParameters pdpParams = mock(PdpParameters.class); doAnswer(new Answer<Object>() { @@ -120,8 +114,6 @@ public class CommonRequestBase { when(timers.register(any(), any())).thenReturn(timer); - when(daoFactory.create()).thenReturn(dao); - PdpStateChangeParameters stateParams = mock(PdpStateChangeParameters.class); when(stateParams.getMaxRetryCount()).thenReturn(RETRIES); when(pdpParams.getStateChangeParameters()).thenReturn(stateParams); @@ -134,7 +126,7 @@ public class CommonRequestBase { .setResponseDispatcher(dispatcher).setTimers(timers); mapParams = PdpModifyRequestMapParams.builder().modifyLock(lock).pdpPublisher(publisher) - .policyNotifier(notifier).responseDispatcher(dispatcher).daoFactory(daoFactory) + .responseDispatcher(dispatcher) .updateTimers(timers).stateChangeTimers(timers).params(pdpParams) .maxPdpAgeMs(100).build(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java index 7ae4b370..34c20410 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -31,6 +31,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; @@ -46,8 +47,10 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.parameters.CommonTestData; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PdpParameters; import org.onap.policy.pap.main.rest.e2e.End2EndBase; +import org.springframework.beans.factory.annotation.Autowired; /** * Class to perform unit test of {@link PdpHeartbeatListener}. @@ -65,12 +68,16 @@ public class PdpHeartbeatListenerTest extends End2EndBase { private static final String TOPIC = "my-topic"; private Instant timeStamp; + + @Autowired private PdpHeartbeatListener pdpHeartbeatListener; @Test public void testPdpHeartbeatListener() throws CoderException, PfModelException { addGroups("PdpGroups.json"); - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), true); + PapParameterGroup parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(true); // Testing pdp registration success case final PdpStatus status1 = new PdpStatus(); @@ -219,14 +226,14 @@ public class PdpHeartbeatListenerTest extends End2EndBase { List<ToscaPolicy> policies = new ArrayList<>(); policies.add(polA); policies.add(polB); - final CommonTestData testData = new CommonTestData(); - PdpParameters params = testData.getPapParameterGroup(1).getPdpParameters(); - List<ToscaConceptIdentifier> polsUndep = policies.stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); - PdpStatusMessageHandler handler = new PdpStatusMessageHandler(params, true); - PdpUpdate update10 = handler.createPdpUpdateMessage( - status3.getPdpGroup(), new PdpSubGroup(), "pdp_2", - policies, polsUndep); + final PapParameterGroup testGroup = new CommonTestData().getPapParameterGroup(1); + testGroup.setSavePdpStatisticsInDb(true); + List<ToscaConceptIdentifier> polsUndep = + policies.stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList()); + PdpStatusMessageHandler handler = new PdpStatusMessageHandler(testGroup, pdpGroupService, + pdpStatisticsService); + PdpUpdate update10 = + handler.createPdpUpdateMessage(status3.getPdpGroup(), new PdpSubGroup(), "pdp_2", policies, polsUndep); assertSame(update10.getPoliciesToBeDeployed(), policies); assertSame(update10.getPoliciesToBeUndeployed(), polsUndep); assertThat(update10.getPoliciesToBeDeployed()).isInstanceOf(List.class); @@ -235,7 +242,9 @@ public class PdpHeartbeatListenerTest extends End2EndBase { @Test public void testPdpStatistics() throws CoderException, PfModelException, ParseException { addGroups("PdpGroups.json"); - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), true); + PapParameterGroup parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(true); timeStamp = Instant.parse("2021-02-12T17:48:01.029211400Z"); // init default pdp group @@ -283,7 +292,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { pdpStatistics03.setTimeStamp(timeStamp); status3.setStatistics(pdpStatistics03); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status3); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Testing pdp statistics failure having the pdpStatistics null in the heartbeat for already registered pdp final PdpStatus status4 = new PdpStatus(); @@ -298,7 +307,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status4.setPolicies(idents4); status4.setStatistics(null); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status4); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Testing pdp statistics failure passing different pdpGroup, PdpSubGroup & pdpInstanceId final PdpStatus status5 = new PdpStatus(); @@ -320,7 +329,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status5.setStatistics(pdpStatistics05); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status5); - verifyPdpStatistics(null, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Test pdp statistics failure passing negative values final PdpStatus status6 = new PdpStatus(); @@ -347,10 +356,12 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status5.setStatistics(pdpStatistics06); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status5); - verifyPdpStatistics(null, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Test pdp statistics save disabled case, sending valid pdp status but count should still remain 1 - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), false); + parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(false); timeStamp = Instant.parse("2021-02-12T17:48:05.029211400Z"); final PdpStatus status7 = new PdpStatus(); status7.setName(PDP_NAME); @@ -370,7 +381,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { pdpStatistics07.setTimeStamp(timeStamp); status7.setStatistics(pdpStatistics07); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status7); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); } @@ -389,7 +400,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { private void verifyPdpStatistics(final String pdpInstanceId, final String pdpGroupName, final String pdpSubGroupName, final int count) throws PfModelException { - final List<PdpStatistics> fetchedPdpStatistics = + final Map<String, Map<String, List<PdpStatistics>>> fetchedPdpStatistics = fetchPdpStatistics(pdpInstanceId, pdpGroupName, pdpSubGroupName); assertEquals(count, fetchedPdpStatistics.size()); } 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 e626d28d..6ff989cd 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 @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -70,6 +71,8 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.msgdata.Request; import org.onap.policy.pap.main.comm.msgdata.RequestListener; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyStatusService; import org.powermock.reflect.Whitebox; @RunWith(MockitoJUnitRunner.class) @@ -105,6 +108,12 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { @Mock private PdpStatusMessageHandler responseHandler; + @Mock + private PdpGroupService pdpGroupService; + + @Mock + private PolicyStatusService policyStatusService; + private MyMap map; private PdpUpdate update; private PdpStateChange change; @@ -135,14 +144,12 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { response.setPolicies(Collections.emptyList()); map = new MyMap(mapParams); - map.setPolicyUndeployer(undeployer); } @Test public void testPdpModifyRequestMap() { assertSame(mapParams, Whitebox.getInternalState(map, "params")); assertSame(lock, Whitebox.getInternalState(map, "modifyLock")); - assertSame(daoFactory, Whitebox.getInternalState(map, "daoFactory")); } @Test @@ -379,7 +386,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { Instant expired = Instant.now().minusSeconds(EXPIRED_SECONDS); group2.getPdpSubgroups().get(0).getPdpInstances().forEach(pdp -> pdp.setLastUpdate(expired)); - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); // run it map.removeExpiredPdps(); @@ -407,25 +414,25 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { PdpGroup group1 = makeGroup(MY_GROUP); group1.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1))); - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); // run it map.removeExpiredPdps(); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(publisher, never()).enqueue(any()); } @Test public void testRemoveExpiredPdps_DaoEx() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenThrow(makeException()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @Test public void testRemoveExpiredPdps_DaoRtEx() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @@ -440,8 +447,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { List<Pdp> pdps = group.getPdpSubgroups().get(0).getPdpInstances(); pdps.get(0).setLastUpdate(expired); pdps.get(2).setLastUpdate(expired); - - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group)); // run it map.removeExpiredPdps(); @@ -469,7 +475,10 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { @Test public void testMakePdpRequests() { // this should invoke the real method without throwing an exception - new PdpModifyRequestMap(mapParams).addRequest(change); + PdpModifyRequestMap reqMap = + new PdpModifyRequestMap(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); + reqMap.initialize(mapParams); + reqMap.addRequest(change); QueueToken<PdpMessage> token = queue.poll(); assertNotNull(token); @@ -621,7 +630,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { assertEquals(1, map.nalloc); // no updates - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); } @Test @@ -753,7 +762,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * @throws Exception if an error occurred */ private List<PdpGroup> getGroupUpdates() throws Exception { - verify(dao).updatePdpGroups(updateCaptor.capture()); + verify(pdpGroupService).updatePdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } @@ -777,7 +786,8 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { private int nalloc = 0; public MyMap(PdpModifyRequestMapParams params) { - super(params); + super(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); + super.initialize(params);; } @Override @@ -785,10 +795,5 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { ++nalloc; return requests; } - - @Override - protected PdpStatusMessageHandler makePdpResponseHandler() { - return responseHandler; - } } } diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java index 8d7a8c15..3b7f7e16 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -45,9 +46,9 @@ import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.PdpPolicyStatusBuilder; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.notification.StatusAction.Action; +import org.onap.policy.pap.main.service.PolicyStatusService; @RunWith(MockitoJUnitRunner.class) public class DeploymentStatusTest { @@ -75,7 +76,7 @@ public class DeploymentStatusTest { private ArgumentCaptor<List<PdpPolicyStatus>> deleted; @Mock - private PolicyModelsProvider provider; + private PolicyStatusService policyStatusService; private DeploymentStatus tracker; @@ -84,7 +85,7 @@ public class DeploymentStatusTest { */ @Before public void setUp() { - tracker = new DeploymentStatus(provider); + tracker = new DeploymentStatus(policyStatusService); // @formatter:off builder = PdpPolicyStatus.builder() @@ -142,7 +143,7 @@ public class DeploymentStatusTest { PdpPolicyStatus status2 = builder.policy(POLICY_B).build(); PdpPolicyStatus status3 = builder.policy(POLICY_A).pdpId(PDP_B).build(); - when(provider.getGroupPolicyStatus(GROUP_A)).thenReturn(List.of(status1, status2, status3)); + when(policyStatusService.getGroupPolicyStatus(GROUP_A)).thenReturn(List.of(status1, status2, status3)); tracker.loadByGroup(GROUP_A); @@ -156,7 +157,7 @@ public class DeploymentStatusTest { // try again - should not reload tracker.loadByGroup(GROUP_A); - verify(provider).getGroupPolicyStatus(anyString()); + verify(policyStatusService).getGroupPolicyStatus(anyString()); } @Test @@ -198,7 +199,7 @@ public class DeploymentStatusTest { tracker.flush(); - verify(provider).cudPolicyStatus(created.capture(), updated.capture(), deleted.capture()); + verify(policyStatusService).cudPolicyStatus(created.capture(), updated.capture(), deleted.capture()); assertThat(sort(created.getValue())).isEqualTo(List.of(create1, create2)); assertThat(sort(updated.getValue())).isEqualTo(List.of(update1, update2)); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java index 9134985c..5fec269a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -41,14 +42,14 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pap.concepts.PolicyStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.QueueToken; +import org.onap.policy.pap.main.service.PolicyStatusService; @RunWith(MockitoJUnitRunner.class) public class PolicyNotifierTest { @@ -61,10 +62,7 @@ public class PolicyNotifierTest { private Publisher<PolicyNotification> publisher; @Mock - private PolicyModelsProviderFactoryWrapper daoFactory; - - @Mock - private PolicyModelsProvider dao; + private PolicyStatusService policyStatusService; @Mock private DeploymentStatus tracker; @@ -92,8 +90,7 @@ public class PolicyNotifierTest { @Before public void setUp() { try { - when(daoFactory.create()).thenReturn(dao); - when(dao.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); + when(policyStatusService.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); notifier = new MyNotifier(publisher); @@ -125,7 +122,8 @@ public class PolicyNotifierTest { @Test public void testProcessResponseString_Ex() throws PfModelException { - doThrow(new PfModelException(Status.BAD_REQUEST, "expected exception")).when(tracker).loadByGroup(anyString()); + doThrow(new PfModelRuntimeException(Status.BAD_REQUEST, "expected exception")).when(tracker) + .loadByGroup(anyString()); assertThatCode(() -> notifier.processResponse(PDP1, GROUP_A, Set.of(), Set.of())).doesNotThrowAnyException(); } @@ -155,20 +153,23 @@ public class PolicyNotifierTest { @Test public void testMakeDeploymentTracker() throws PfModelException { // make real object, which will invoke the real makeXxx() methods - new PolicyNotifier(publisher, daoFactory).processResponse(PDP1, GROUP_A, Set.of(), Set.of()); + PolicyNotifier policyNotifier = new PolicyNotifier(policyStatusService); + policyNotifier.setPublisher(publisher); + policyNotifier.processResponse(PDP1, GROUP_A, Set.of(), Set.of()); - verify(dao).getGroupPolicyStatus(GROUP_A); + verify(policyStatusService).getGroupPolicyStatus(GROUP_A); } private class MyNotifier extends PolicyNotifier { public MyNotifier(Publisher<PolicyNotification> publisher) throws PfModelException { - super(publisher, daoFactory); + super(policyStatusService); + super.setPublisher(publisher); } @Override - protected DeploymentStatus makeDeploymentTracker(PolicyModelsProvider dao) { + protected DeploymentStatus makeDeploymentTracker() { return tracker; } } diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java index b77c5544..c41915d2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -31,10 +32,8 @@ import org.junit.Test; import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.TimerManager; -import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams.PdpModifyRequestMapParamsBuilder; public class TestPdpModifyRequestMapParams { @@ -46,8 +45,6 @@ public class TestPdpModifyRequestMapParams { private PdpParameters pdpParams; private TimerManager updTimers; private TimerManager stateTimers; - private PolicyModelsProviderFactoryWrapper dao; - private PolicyNotifier notifier; /** * Sets up the objects and creates an empty {@link #builder}. @@ -61,12 +58,10 @@ public class TestPdpModifyRequestMapParams { pdpParams = mock(PdpParameters.class); updTimers = mock(TimerManager.class); stateTimers = mock(TimerManager.class); - dao = mock(PolicyModelsProviderFactoryWrapper.class); - notifier = mock(PolicyNotifier.class); builder = PdpModifyRequestMapParams.builder().modifyLock(lock).pdpPublisher(pub).responseDispatcher(disp) .params(pdpParams).stateChangeTimers(stateTimers).updateTimers(updTimers) - .daoFactory(dao).policyNotifier(notifier).maxPdpAgeMs(MAX_PDP_AGE_MS); + .maxPdpAgeMs(MAX_PDP_AGE_MS); } @Test @@ -79,8 +74,6 @@ public class TestPdpModifyRequestMapParams { assertSame(pdpParams, params.getParams()); assertSame(updTimers, params.getUpdateTimers()); assertSame(stateTimers, params.getStateChangeTimers()); - assertSame(dao, params.getDaoFactory()); - assertSame(notifier, params.getPolicyNotifier()); } @Test @@ -133,16 +126,4 @@ public class TestPdpModifyRequestMapParams { assertThatIllegalArgumentException().isThrownBy(() -> builder.updateTimers(null).build().validate()) .withMessageContaining("update"); } - - @Test - public void testValidate_MissingDaoFactory() { - assertThatIllegalArgumentException().isThrownBy(() -> builder.daoFactory(null).build().validate()) - .withMessageContaining("DAO"); - } - - @Test - public void testValidate_MissingNotifier() { - assertThatIllegalArgumentException().isThrownBy(() -> builder.policyNotifier(null).build().validate()) - .withMessageContaining("notifier"); - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index 9673c295..e42cfd21 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -111,7 +111,7 @@ public abstract class CommonPapRestServer { @DynamicPropertySource static void registerPgProperties(DynamicPropertyRegistry registry) { - registry.add("pap.databaseProviderParameters.databaseUrl", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); + registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); registry.add("server.ssl.enabled", () -> "true"); registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java index 26e44d80..153a2bfa 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -49,13 +50,15 @@ import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpStateChange; 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.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; /** * Super class for TestPdpGroupDeployProviderXxx classes. @@ -65,11 +68,19 @@ public class ProviderSuper { public static final String DEFAULT_USER = "PAP_TEST"; @Mock - protected PolicyModelsProvider dao; + protected PdpGroupService pdpGroupService; @Mock - protected PolicyNotifier notifier; + protected PolicyStatusService policyStatusService; + + @Mock + protected PolicyAuditService policyAuditService; + @Mock + protected ToscaServiceTemplateService toscaService; + + @Mock + protected PolicyNotifier notifier; /** * Used to capture input to dao.updatePdpGroups() and dao.createPdpGroups(). @@ -79,7 +90,6 @@ public class ProviderSuper { protected Object lockit; protected PdpModifyRequestMap reqmap; - protected PolicyModelsProviderFactoryWrapper daofact; protected ToscaPolicy policy1; protected PapStatisticsManager statsmanager; @@ -96,26 +106,35 @@ public class ProviderSuper { reqmap = mock(PdpModifyRequestMap.class); lockit = new Object(); - daofact = mock(PolicyModelsProviderFactoryWrapper.class); policy1 = loadPolicy("policy.json"); statsmanager = mock(PapStatisticsManager.class); - when(daofact.create()).thenReturn(dao); - List<PdpGroup> groups = loadGroups("groups.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); - when(dao.createPdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); - when(dao.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); + when(pdpGroupService.createPdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); + when(pdpGroupService.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgument(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); - Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier); Registry.register(PapConstants.REG_STATISTICS_MANAGER, statsmanager); } + /** + * Initialize services to the provider for tests. + * + * @param prov the provider + */ + public void initialize(ProviderBase prov) { + prov.setPdpGroupService(pdpGroupService); + prov.setPolicyAuditService(policyAuditService); + prov.setPolicyStatusService(policyStatusService); + prov.setToscaService(toscaService); + prov.setPolicyNotifier(notifier); + prov.initialize(); + } + protected void assertGroup(List<PdpGroup> groups, String name) { PdpGroup group = groups.remove(0); @@ -138,7 +157,7 @@ public class ProviderSuper { * @throws Exception if an error occurred */ protected List<PdpGroup> getGroupCreates() throws Exception { - verify(dao).createPdpGroups(updateCaptor.capture()); + verify(pdpGroupService).createPdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } @@ -150,7 +169,7 @@ public class ProviderSuper { * @throws Exception if an error occurred */ protected List<PdpGroup> getGroupUpdates() throws Exception { - verify(dao).updatePdpGroups(updateCaptor.capture()); + verify(pdpGroupService).updatePdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index 9a0f5702..7666dc2a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -1,563 +1,561 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. 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; - -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.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.TreeMap; -import javax.ws.rs.core.Response.Status; -import org.assertj.core.api.Assertions; -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.pdp.concepts.PdpGroup; -import org.onap.policy.models.pdp.concepts.PdpGroups; -import org.onap.policy.models.pdp.concepts.PdpStateChange; -import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PapConstants; - -public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { - private static final String EXPECTED_EXCEPTION = "expected exception"; - - private static final String PDP2 = "pdpB"; - private static final String PDP4 = "pdpD"; - - private PdpGroupCreateOrUpdateProvider prov; - - @AfterClass - public static void tearDownAfterClass() { - Registry.newRegistry(); - } - - /** - * Configures mocks and objects. - * - * @throws Exception if an error occurs - */ - @Before - @Override - public void setUp() throws Exception { - - super.setUp(); - - when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); - - prov = new PdpGroupCreateOrUpdateProvider(); - prov.initialize(); - } - - @Test - public void testCreateOrUpdateGroups() throws Exception { - prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); - - // no groups, so no action should have been taken - assertNoGroupAction(); - } - - @Test - public void testCreateOrUpdateGroups_InvalidRequest() throws Exception { - assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) - .hasMessageContaining("is null"); - - assertNoGroupAction(); - } - - @Test - public void testCreateOrUpdate_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - - assertNoGroupAction(); - } - - @Test - public void testAddGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup group = groups.getGroups().get(0); - group.setPdpGroupState(PdpState.PASSIVE); - - prov.createOrUpdateGroups(groups); - - // should not have updated the state - assertEquals(PdpState.PASSIVE, group.getPdpGroupState()); - - assertSame(group, getGroupCreates().get(0)); - } - - @Test - public void testAddGroup_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - - assertNoGroupAction(); - } - - @Test - public void testAddGroup_InvalidSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("unknown policy type"); - - assertNoGroupAction(); - } - - @Test - public void testValidateGroupOnly_NullState() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(null); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Active() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Passive() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Invalid() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - } - - @Test - public void testUpdateGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - // DB group = new group - PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertNoGroupAction(); - } - - @Test - public void testUpdateGroup_PropertiesChanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - group.setProperties(new TreeMap<>()); - - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - @Test - public void testUpdateGroup_NewDescription() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - group.setDescription("old description"); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertGroupUpdateOnly(group); - - assertEquals("my description", group.getDescription()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateGroup_NewState() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - group.setPdpGroupState(PdpState.TEST); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertGroupUpdateOnly(group); - - assertEquals(PdpState.ACTIVE, group.getPdpGroupState()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateGroup_NewSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateGroup_UpdatedSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - // something different in this subgroup - group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception { - PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0)); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); - - PdpGroups groups = loadPdpGroups("createGroups.json"); - - prov.createOrUpdateGroups(groups); - - // verify that DB group was updated - List<PdpGroup> updates = getGroupUpdates(); - assertEquals(1, updates.size()); - dbgroup = updates.get(0); - - PdpGroup newgrp = groups.getGroups().get(0); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), dbgroup.toString()); - - // no deployment notifications - checkEmptyNotification(); - - // this requires a PDP UPDATE message - List<PdpUpdate> pdpUpdates = getUpdateRequests(2); - assertEquals(2, pdpUpdates.size()); - - PdpUpdate pdpUpdate = pdpUpdates.get(0); - assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); - assertEquals(PDP2, pdpUpdate.getName()); - assertNull(pdpUpdate.getPdpGroup()); - - pdpUpdate = pdpUpdates.get(1); - assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); - assertEquals(PDP4, pdpUpdate.getName()); - assertNull(pdpUpdate.getPdpGroup()); - - // it also requires a PDP STATE-CHANGE message - List<PdpStateChange> changes = getStateChangeRequests(2); - assertEquals(2, changes.size()); - - PdpStateChange change = changes.get(0); - assertEquals(PapConstants.PAP_NAME, change.getSource()); - assertEquals(PDP2, change.getName()); - assertEquals(PdpState.PASSIVE, change.getState()); - - change = changes.get(1); - assertEquals(PapConstants.PAP_NAME, change.getSource()); - assertEquals(PDP4, change.getName()); - assertEquals(PdpState.PASSIVE, change.getState()); - } - - @Test - public void testUpdateField_Unchanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertNoGroupAction(); - } - - @Test - public void testUpdateField_WasNull() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - group.setDescription(null); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateField_NowNull() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setDescription(null); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateField_Changed() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setDescription(group.getDescription() + "-changed"); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testAddSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - - PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); - newsub.setCurrentInstanceCount(0); - newsub.setPdpInstances(new ArrayList<>(0)); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - /** - * Tests addSubgroup() when the new subgroup has a wild-card policy type. - * - * @throws Exception if an error occurs - */ - @Test - public void testAddSubGroupWildCardPolicyType() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); - when(dao.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList()); - - PdpGroups groups = loadPdpGroups("createGroupsWildCard.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - - PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); - newsub.setCurrentInstanceCount(0); - newsub.setPdpInstances(new ArrayList<>(0)); - - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type"); - } - - @Test - public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); - when(dao.getPolicyTypeList(any(), any())).thenThrow(exc); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc); - } - - @Test - public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) - .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json")); - - PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json"); - - prov.createOrUpdateGroups(reqgroups); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), dbgroup.toString()); - } - - @Test - public void testUpdateSubGroup_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - // change properties - newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - @Test - public void testUpdateSubGroup_SupportedPolicies() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes() - .add(new ToscaConceptIdentifier("typeX.*", "9.8.7")); - - // the group is updated with a new supported policy type in subgroup - assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); - prov.createOrUpdateGroups(groups); - // PdpGroup update doesn't allow supported policy type modifications - // during pdp group update, the ones in db is maintained - assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateSubGroup_DesiredCount() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateSubGroup_Unchanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), group.toString()); - - // no notifications - checkEmptyNotification(); - - // no group updates - assertNoGroupAction(); - } - - @Test - public void testValidateSubGroup_PropertiesMismatch() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setProperties(new TreeMap<>()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - private void assertNoGroupAction() throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); - verify(reqmap, never()).addRequest(any(), any()); - } - - private void assertGroupUpdateOnly(PdpGroup group) throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(reqmap, never()).addRequest(any(), any()); - - List<PdpGroup> updates = getGroupUpdates(); - assertEquals(Arrays.asList(group), updates); - } -} +/*
+ * ============LICENSE_START=======================================================
+ * ONAP PAP
+ * ================================================================================
+ * Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property.
+ * Modifications Copyright (C) 2021-2022 Bell Canada. 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;
+
+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.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.TreeMap;
+import javax.ws.rs.core.Response.Status;
+import org.assertj.core.api.Assertions;
+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.pdp.concepts.PdpGroup;
+import org.onap.policy.models.pdp.concepts.PdpGroups;
+import org.onap.policy.models.pdp.concepts.PdpStateChange;
+import org.onap.policy.models.pdp.concepts.PdpSubGroup;
+import org.onap.policy.models.pdp.concepts.PdpUpdate;
+import org.onap.policy.models.pdp.enums.PdpState;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+import org.onap.policy.pap.main.PapConstants;
+
+public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper {
+ private static final String EXPECTED_EXCEPTION = "expected exception";
+
+ private static final String PDP2 = "pdpB";
+ private static final String PDP4 = "pdpD";
+
+ private PdpGroupCreateOrUpdateProvider prov;
+
+
+ + @AfterClass
+ public static void tearDownAfterClass() {
+ Registry.newRegistry();
+ }
+
+ /**
+ * Configures mocks and objects.
+ *
+ * @throws Exception if an error occurs
+ */
+ @Before
+ @Override
+ public void setUp() throws Exception {
super.setUp();
+ prov = new PdpGroupCreateOrUpdateProvider();
+ super.initialize(prov);
+ when(toscaService.getPolicyTypeList("typeA", "100.2.3"))
+ .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json")));
}
+
+ @Test
+ public void testCreateOrUpdateGroups() throws Exception {
+ prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json"));
+
+ // no groups, so no action should have been taken
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testCreateOrUpdateGroups_InvalidRequest() throws Exception {
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("is null");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testCreateOrUpdate_Invalid() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("pdpGroupState");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testAddGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup group = groups.getGroups().get(0);
+ group.setPdpGroupState(PdpState.PASSIVE);
+
+ prov.createOrUpdateGroups(groups);
+
+ // should not have updated the state
+ assertEquals(PdpState.PASSIVE, group.getPdpGroupState());
+
+ assertSame(group, getGroupCreates().get(0));
+ }
+
+ @Test
+ public void testAddGroup_Invalid() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("pdpGroupState");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testAddGroup_InvalidSubGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+
+ groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99");
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("unknown policy type");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testValidateGroupOnly_NullState() {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(null);
+ Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testValidateGroupOnly_Active() {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE);
+ Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testValidateGroupOnly_Passive() {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE);
+ Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testValidateGroupOnly_Invalid() {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("pdpGroupState");
+ }
+
+ @Test
+ public void testUpdateGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+
+ // DB group = new group
+ PdpGroup group = new PdpGroup(groups.getGroups().get(0));
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testUpdateGroup_PropertiesChanged() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+
+ PdpGroup group = new PdpGroup(groups.getGroups().get(0));
+ group.setProperties(new TreeMap<>());
+
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("properties");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testUpdateGroup_NewDescription() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ group.setDescription("old description");
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ assertGroupUpdateOnly(group);
+
+ assertEquals("my description", group.getDescription());
+ assertEquals(newgrp.toString(), group.toString());
+ }
+
+ @Test
+ public void testUpdateGroup_NewState() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ group.setPdpGroupState(PdpState.TEST);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ assertGroupUpdateOnly(group);
+
+ assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
+ assertEquals(newgrp.toString(), group.toString());
+ }
+
+ @Test
+ public void testUpdateGroup_NewSubGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+ PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ PdpGroup newgrp = groups.getGroups().get(0);
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testUpdateGroup_UpdatedSubGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ // something different in this subgroup
+ group.getPdpSubgroups().get(0).setDesiredInstanceCount(10);
+
+ prov.createOrUpdateGroups(groups);
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception {
+ PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0));
+ when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup));
+
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+
+ prov.createOrUpdateGroups(groups);
+
+ // verify that DB group was updated
+ List<PdpGroup> updates = getGroupUpdates();
+ assertEquals(1, updates.size());
+ dbgroup = updates.get(0);
+
+ PdpGroup newgrp = groups.getGroups().get(0);
+
+ Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
+ Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies());
+
+ assertEquals(newgrp.toString(), dbgroup.toString());
+
+ // no deployment notifications
+ checkEmptyNotification();
+
+ // this requires a PDP UPDATE message
+ List<PdpUpdate> pdpUpdates = getUpdateRequests(2);
+ assertEquals(2, pdpUpdates.size());
+
+ PdpUpdate pdpUpdate = pdpUpdates.get(0);
+ assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource());
+ assertEquals(PDP2, pdpUpdate.getName());
+ assertNull(pdpUpdate.getPdpGroup());
+
+ pdpUpdate = pdpUpdates.get(1);
+ assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource());
+ assertEquals(PDP4, pdpUpdate.getName());
+ assertNull(pdpUpdate.getPdpGroup());
+
+ // it also requires a PDP STATE-CHANGE message
+ List<PdpStateChange> changes = getStateChangeRequests(2);
+ assertEquals(2, changes.size());
+
+ PdpStateChange change = changes.get(0);
+ assertEquals(PapConstants.PAP_NAME, change.getSource());
+ assertEquals(PDP2, change.getName());
+ assertEquals(PdpState.PASSIVE, change.getState());
+
+ change = changes.get(1);
+ assertEquals(PapConstants.PAP_NAME, change.getSource());
+ assertEquals(PDP4, change.getName());
+ assertEquals(PdpState.PASSIVE, change.getState());
+ }
+
+ @Test
+ public void testUpdateField_Unchanged() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testUpdateField_WasNull() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ group.setDescription(null);
+
+ prov.createOrUpdateGroups(groups);
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testUpdateField_NowNull() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ newgrp.setDescription(null);
+
+ prov.createOrUpdateGroups(groups);
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testUpdateField_Changed() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ newgrp.setDescription(group.getDescription() + "-changed");
+
+ prov.createOrUpdateGroups(groups);
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testAddSubGroup() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+ PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ PdpGroup newgrp = groups.getGroups().get(0);
+
+ PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1);
+ newsub.setCurrentInstanceCount(0);
+ newsub.setPdpInstances(new ArrayList<>(0));
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ /**
+ * Tests addSubgroup() when the new subgroup has a wild-card policy type.
+ *
+ * @throws Exception if an error occurs
+ */
+ @Test
+ public void testAddSubGroupWildCardPolicyType() throws Exception {
+ when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json"));
+ when(toscaService.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList());
+
+ PdpGroups groups = loadPdpGroups("createGroupsWildCard.json");
+ PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ PdpGroup newgrp = groups.getGroups().get(0);
+
+ PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1);
+ newsub.setCurrentInstanceCount(0);
+ newsub.setPdpInstances(new ArrayList<>(0));
+
+ assertEquals(newgrp.toString(), group.toString());
+ }
+
+ @Test
+ public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+ PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList());
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type");
+ }
+
+ @Test
+ public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroupsNewSub.json");
+ PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION);
+ when(toscaService.getPolicyTypeList(any(), any())).thenThrow(exc);
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc);
+ }
+
+ @Test
+ public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup dbgroup = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup));
+
+ when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
+ .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json"));
+
+ PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json");
+
+ prov.createOrUpdateGroups(reqgroups);
+
+ Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
+ Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies());
+
+ assertEquals(newgrp.toString(), dbgroup.toString());
+ }
+
+ @Test
+ public void testUpdateSubGroup_Invalid() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ // change properties
+ newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>());
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("properties");
+
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testUpdateSubGroup_SupportedPolicies() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes()
+ .add(new ToscaConceptIdentifier("typeX.*", "9.8.7"));
+
+ // the group is updated with a new supported policy type in subgroup
+ assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size());
+ prov.createOrUpdateGroups(groups);
+ // PdpGroup update doesn't allow supported policy type modifications
+ // during pdp group update, the ones in db is maintained
+ assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size());
+ assertEquals(newgrp.toString(), group.toString());
+ }
+
+ @Test
+ public void testUpdateSubGroup_DesiredCount() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20);
+
+ prov.createOrUpdateGroups(groups);
+
+ assertEquals(newgrp.toString(), group.toString());
+ assertGroupUpdateOnly(group);
+ }
+
+ @Test
+ public void testUpdateSubGroup_Unchanged() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ prov.createOrUpdateGroups(groups);
+
+ Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
+ Collections.sort(group.getPdpSubgroups().get(0).getPolicies());
+
+ assertEquals(newgrp.toString(), group.toString());
+
+ // no notifications
+ checkEmptyNotification();
+
+ // no group updates
+ assertNoGroupAction();
+ }
+
+ @Test
+ public void testValidateSubGroup_PropertiesMismatch() throws Exception {
+ PdpGroups groups = loadPdpGroups("createGroups.json");
+ PdpGroup newgrp = groups.getGroups().get(0);
+ PdpGroup group = new PdpGroup(newgrp);
+ when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
+
+ newgrp.setProperties(new TreeMap<>());
+
+ assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("properties");
+
+ assertNoGroupAction();
+ }
+
+ private void assertNoGroupAction() throws Exception {
+ verify(pdpGroupService, never()).createPdpGroups(any());
+ verify(pdpGroupService, never()).updatePdpGroups(any());
+ verify(reqmap, never()).addRequest(any(), any());
+ }
+
+ private void assertGroupUpdateOnly(PdpGroup group) throws Exception {
+ verify(pdpGroupService, never()).createPdpGroups(any());
+ verify(reqmap, never()).addRequest(any(), any());
+
+ List<PdpGroup> updates = getGroupUpdates();
+ assertEquals(Arrays.asList(group), updates);
+ }
+}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index 3e9eda8a..449d48f2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -47,6 +47,7 @@ import org.mockito.Captor; import org.mockito.Mock; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -84,14 +85,14 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { @Before @Override public void setUp() throws Exception { - super.setUp(); + prov = new MyProvider(); + super.initialize(prov); ident = policy1.getIdentifier(); optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null); fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion()); - prov = new MyProvider(); updater = prov.makeUpdater(session, policy1, fullIdent); } @@ -144,12 +145,12 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testDeleteGroup_DaoEx() throws Exception { + public void testDeleteGroup_Ex() throws Exception { PdpGroup group = loadGroup("deleteGroup.json"); when(session.getGroup(GROUP1_NAME)).thenReturn(group); - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); doThrow(ex).when(session).deleteGroupFromDb(group); assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex); @@ -162,15 +163,15 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { */ @Test public void testUndeploy_Full() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); PdpGroup group = loadGroup("undeploy.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider(); - deleteProvider.initialize(); + super.initialize(deleteProvider); deleteProvider.undeploy(fullIdent, DEFAULT_USER); // should have updated the old group diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index 28e515f3..29c06f76 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -89,12 +89,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void setUp() throws Exception { super.setUp(); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); - when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); - prov = new PdpGroupDeployProvider(); - prov.initialize(); + super.initialize(prov); + + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); } /** @@ -105,14 +105,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // add new policies List<ToscaConceptIdentifier> policies = newgrp.getPdpSubgroups().get(0).getPolicies(); policies.add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); // add = POST @@ -139,12 +139,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // policy that should be left final ToscaConceptIdentifier policyId1 = policies.remove(0); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); DeploymentGroups depgroups = toDeploymentGroups(groups); @@ -173,7 +173,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // put policy3 into db subgroup subgrp.getPolicies().add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // now make the subgrp reflect our final expectation subgrp.getPolicies().remove(1); @@ -197,7 +197,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { DeploymentGroups depgroups = new DeploymentGroups(); depgroups.setGroups(Arrays.asList(depgroup)); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy2.json")); prov.updateGroupPolicies(depgroups, DEFAULT_USER); @@ -211,7 +211,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -245,7 +245,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { String groupName = groups.getGroups().get(0).getName(); // group not found - when(dao.getPdpGroups(groupName)).thenReturn(Collections.emptyList()); + when(pdpGroupService.getPdpGroups(groupName)).thenReturn(Collections.emptyList()); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining(groupName) @@ -260,7 +260,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // DB group = new group PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); @@ -271,7 +271,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testUpdateGroup_NewSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("deployGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("pdpTypeB") @@ -285,7 +285,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -304,10 +304,10 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // group has no policies yet group.getPdpSubgroups().get(0).getPolicies().clear(); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // unknown policy - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class) @@ -329,7 +329,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.getPdpSubgroups().add(subgrp2); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // add two new policies ToscaConceptIdentifier policyId2 = new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION); @@ -338,7 +338,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { ToscaConceptIdentifier policyId3 = new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION); subgrp.getPolicies().add(policyId3); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); @@ -361,7 +361,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // use version prefix PdpSubGroup subgrp = newgrp.getPdpSubgroups().get(0); @@ -388,7 +388,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // use incorrect version prefix newgrp.getPdpSubgroups().get(0).getPolicies().get(0).setVersion("9"); @@ -404,7 +404,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER); @@ -425,13 +425,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // arrange for DB policy version to be different PdpSubGroup dbsubgrp = dbgroup.getPdpSubgroups().get(0); dbsubgrp.getPolicies().get(0).setVersion("9.9.9"); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("different version already deployed"); @@ -444,7 +444,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); final DeploymentGroups groups = toDeploymentGroups(dbgroups); @@ -456,7 +456,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // DB has a different supported type dbsubgrp.getSupportedPolicyTypes().get(0).setName("some-other-type"); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); assertThatThrownBy(() -> prov.updateGroupPolicies(groups, DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName()) @@ -515,9 +515,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { */ @Test public void testDeployPoliciesWildCard() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); policy1.setName("policy.some"); policy1.setVersion(POLICY1_VERSION); @@ -544,17 +544,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeploySimplePolicies_DaoEx() throws Exception { - PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getFilteredPdpGroups(any())).thenThrow(exc); - - assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc); - } - - @Test - public void testDeploySimplePolicies_DaoPfRtEx() throws Exception { + public void testDeploySimplePolicies_PfRtEx() throws Exception { PfModelRuntimeException exc = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getFilteredPdpGroups(any())).thenThrow(exc); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(exc); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc); } @@ -562,7 +554,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testDeploySimplePolicies_RuntimeEx() throws Exception { RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(exc); + when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasCause(exc); @@ -570,7 +562,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testDeploySimplePolicies_NoGroups() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); @@ -587,9 +579,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PapStatisticsManager mgr = new PapStatisticsManager(); Registry.register(PapConstants.REG_STATISTICS_MANAGER, mgr); - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); prov.deployPolicies(loadRequest("multiple_requests.json"), DEFAULT_USER); - assertEquals(mgr.getTotalPolicyDeployCount(), 3); + assertEquals(3, mgr.getTotalPolicyDeployCount()); Registry.unregister(PapConstants.REG_STATISTICS_MANAGER); Registry.register(PapConstants.REG_STATISTICS_MANAGER, statsmanager); @@ -609,7 +601,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * Last subgroup matches. */ - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); prov.deployPolicies(loadRequest(), DEFAULT_USER); @@ -627,14 +619,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testMakeUpdater_PolicyVersionMismatch() throws Exception { // subgroup has a different version of the Policy - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json")); PdpDeployPolicies req = loadRequest(); assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class) .hasMessageContaining("pdpTypeC").hasMessageContaining("different version already deployed"); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } @@ -642,14 +634,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testMakeUpdater_NoPdps() throws Exception { // subgroup has no PDPs - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); PdpDeployPolicies req = loadRequest(); assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class) .hasMessage("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs"); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } @@ -664,13 +656,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } private void assertNoGroupAction() throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(), any()); } private void assertGroupUpdate(PdpGroup group, PdpSubGroup subgrp) throws Exception { - verify(dao, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); assertEquals(0, getStateChangeRequests(1).size()); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index b236c56b..0040beae 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,8 +23,6 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; @@ -45,9 +43,7 @@ import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.Pdps; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.service.PdpGroupService; import org.springframework.http.HttpStatus; /** @@ -59,8 +55,7 @@ import org.springframework.http.HttpStatus; public class TestPdpGroupHealthCheckProvider { @Mock - private PolicyModelsProvider dao; - private PolicyModelsProviderFactoryWrapper daofact; + private PdpGroupService pdpGroupService; private List<PdpGroup> groups; private Coder coder = new StandardCoder(); @@ -71,19 +66,14 @@ public class TestPdpGroupHealthCheckProvider { public void setUp() throws Exception { Registry.newRegistry(); - daofact = mock(PolicyModelsProviderFactoryWrapper.class); - when(daofact.create()).thenReturn(dao); - groups = loadFile("pdpGroup.json").getGroups(); - when(dao.getPdpGroups(any())).thenReturn(groups); - - Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); + when(pdpGroupService.getPdpGroups()).thenReturn(groups); } @Test public void testFetchPdpGroupHealthStatus() throws Exception { - final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(); + final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(pdpGroupService); final Pair<HttpStatus, Pdps> pair = provider.fetchPdpGroupHealthStatus(); assertEquals(HttpStatus.OK, pair.getLeft()); verifyPdps(pair.getRight().getPdpList(), groups); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java index b33c0ef6..4f844fbc 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -52,7 +53,7 @@ public class TestPolicyAuditManager extends ProviderSuper { @Before public void setUp() throws Exception { super.setUp(); - auditManager = new PolicyAuditManager(dao); + auditManager = new PolicyAuditManager(policyAuditService); } @AfterClass @@ -88,7 +89,7 @@ public class TestPolicyAuditManager extends ProviderSuper { assertThat(auditManager.getAuditRecords()).hasSize(1); - doThrow(PfModelRuntimeException.class).when(dao).createAuditRecords(any()); + doThrow(PfModelRuntimeException.class).when(policyAuditService).createAuditRecords(any()); auditManager.saveRecordsToDb(); assertThat(auditManager.getAuditRecords()).isNotEmpty(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java deleted file mode 100644 index 51bea02a..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. 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; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -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.PolicyAudit; -import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; - -public class TestPolicyAuditProvider extends ProviderSuper { - private static final String TEST_GROUP = "testGroup"; - private static final String TEST_PDP_TYPE = "testPdpType"; - private static final ToscaConceptIdentifier POLICY_A = new ToscaConceptIdentifier("PolicyA", "1.0.0"); - private static final ToscaConceptIdentifier POLICY_B = new ToscaConceptIdentifier("PolicyB", "2.0.0"); - - private PolicyAuditProvider provider; - - @AfterClass - public static void tearDownAfterClass() { - Registry.newRegistry(); - } - - @Override - @Before - public void setUp() throws Exception { - - super.setUp(); - provider = new PolicyAuditProvider(); - provider.initialize(); - } - - @Test - public void testGetAuditRecords() throws PfModelException { - - AuditFilter auditFilter = AuditFilter.builder().recordNum(5).fromDate(null).toDate(null).build(); - - buildAuditRecords(auditFilter); - - List<PolicyAudit> result = new ArrayList<>(provider.getAuditRecords(auditFilter)); - validateAuditRecords(result, 2); - } - - private void buildAuditRecords(AuditFilter auditFilter) { - PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) - .policy(POLICY_A).action(AuditAction.DEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER) - .build(); - - PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) - .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER) - .build(); - - if (auditFilter.getName() == null) { - when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1, audit2)); - } else { - when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1)); - } - - } - - private void validateAuditRecords(List<PolicyAudit> result, int count) { - assertThat(result).hasSize(count); - for (PolicyAudit audit : result) { - if (audit.getAuditId() == 123L) { - assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP); - assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE); - assertThat(audit.getPolicy()).isEqualTo(POLICY_A); - assertThat(audit.getAction()).isEqualTo(AuditAction.DEPLOYMENT); - assertThat(audit.getUser()).isEqualTo(DEFAULT_USER); - } else if (audit.getAuditId() == 456L) { - assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP); - assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE); - assertThat(audit.getPolicy()).isEqualTo(POLICY_B); - assertThat(audit.getAction()).isEqualTo(AuditAction.UNDEPLOYMENT); - assertThat(audit.getUser()).isEqualTo(DEFAULT_USER); - } - } - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java index 13deef40..04d4cf91 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2020 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Corp. - * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2022 Bell Canada. 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. @@ -25,7 +25,6 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.io.File; @@ -55,11 +54,10 @@ import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.enums.PdpHealthStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.service.PdpGroupService; import org.onap.policy.pap.main.startstop.PapActivator; import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; @@ -73,10 +71,7 @@ public class TestPolicyComponentsHealthCheckProvider { private static final String HEALTHY = "healthy"; @Mock - private PolicyModelsProvider dao; - - @Mock - private PolicyModelsProviderFactoryWrapper daofact; + private PdpGroupService pdpGroupService; @Mock private HttpClientFactory clientFactory; @@ -116,11 +111,9 @@ public class TestPolicyComponentsHealthCheckProvider { @Before public void setUp() throws Exception { groups = loadPdpGroupsFromFile().getGroups(); - when(dao.getPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getPdpGroups()).thenReturn(groups); - when(daofact.create()).thenReturn(dao); Registry.newRegistry(); - Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); when(papActivator.isAlive()).thenReturn(true); Registry.register(PapConstants.REG_PAP_ACTIVATOR, papActivator); @@ -153,7 +146,7 @@ public class TestPolicyComponentsHealthCheckProvider { clients.add(client2); clients.add(client3); PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME); - provider = new PolicyComponentsHealthCheckProvider(); + provider = new PolicyComponentsHealthCheckProvider(papParameterGroup, pdpGroupService); ReflectionTestUtils.setField(provider, "papParameterGroup", papParameterGroup); provider.initializeClientHealthCheckExecutorService(); ReflectionTestUtils.setField(provider, "clients", clients); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index 8f09b7e3..1f2c08ed 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -59,7 +59,6 @@ public class TestPolicyStatusProvider extends ProviderSuper { private PolicyStatusProvider prov; - @AfterClass public static void tearDownAfterClass() { Registry.newRegistry(); @@ -76,8 +75,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { super.setUp(); - prov = new PolicyStatusProvider(); - prov.initialize(); + prov = new PolicyStatusProvider(policyStatusService); } @Test @@ -242,7 +240,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { builder.deploy(true); // @formatter:off - when(dao.getAllPolicyStatus()).thenReturn(List.of( + when(policyStatusService.getAllPolicyStatus()).thenReturn(List.of( builder.policy(POLICY_A).pdpId(PDP_A).build(), builder.policy(POLICY_A).pdpId(PDP_B).build(), notDeployed, @@ -264,7 +262,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { ToscaConceptIdentifierOptVersion optIdent = new ToscaConceptIdentifierOptVersion(POLICY_A); // @formatter:off - when(dao.getAllPolicyStatus(optIdent)).thenReturn(List.of( + when(policyStatusService.getAllPolicyStatus(optIdent)).thenReturn(List.of( builder.policy(POLICY_A).pdpId(PDP_A).build(), notDeployed, builder.policy(POLICY_A).pdpId(PDP_C).build() diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index 5046181c..434863b5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -71,7 +71,6 @@ public class TestProviderBase extends ProviderSuper { private MyProvider prov; - @AfterClass public static void tearDownAfterClass() { Registry.newRegistry(); @@ -85,20 +84,16 @@ public class TestProviderBase extends ProviderSuper { @Override @Before public void setUp() throws Exception { - super.setUp(); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); - prov = new MyProvider(); - prov.initialize(); + super.initialize(prov); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); } @Test public void testProviderBase() { assertSame(lockit, Whitebox.getInternalState(prov, "updateLock")); assertSame(reqmap, Whitebox.getInternalState(prov, "requestMap")); - assertSame(daofact, Whitebox.getInternalState(prov, "daoFactory")); } @Test @@ -113,17 +108,9 @@ public class TestProviderBase extends ProviderSuper { } @Test - public void testProcess_CreateEx() throws Exception { - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); - - assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); - } - - @Test public void testProcess_PfRtEx() throws Exception { PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); + when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); } @@ -131,7 +118,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcess_RuntimeEx() throws Exception { RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); + when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isInstanceOf(PfModelException.class) .hasMessage("request failed").hasCause(ex); @@ -139,19 +126,20 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcessPolicy_NoGroups() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); - SessionData session = new SessionData(dao, DEFAULT_USER); + SessionData session = + new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService); ToscaConceptIdentifierOptVersion ident = new ToscaConceptIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION); assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PfModelException.class) - .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); + .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); } @Test public void testGetPolicy() throws Exception { PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(exc); + when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); ToscaConceptIdentifierOptVersion req = loadRequest(); assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class) @@ -160,7 +148,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testGetPolicy_NotFound() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); ToscaConceptIdentifierOptVersion req = loadRequest(); assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class) @@ -171,7 +159,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testGetGroup() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) .thenReturn(loadGroups("groups.json")); prov.process(loadRequest(), this::handle); @@ -193,7 +181,7 @@ public class TestProviderBase extends ProviderSuper { * Last subgroup matches. */ - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); prov.clear(); prov.add(false, true, false, true); @@ -225,7 +213,7 @@ public class TestProviderBase extends ProviderSuper { * Should generate updates to pdp1, pdp2, and pdp3. */ - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) .thenReturn(loadPolicies("upgradeGroupPolicy2.json")) .thenReturn(loadPolicies("upgradeGroupPolicy3.json")) .thenReturn(loadPolicies("upgradeGroupPolicy4.json")); @@ -238,7 +226,7 @@ public class TestProviderBase extends ProviderSuper { * request */ // @formatter:off - when(dao.getFilteredPdpGroups(any())) + when(pdpGroupService.getFilteredPdpGroups(any())) .thenReturn(groups1).thenReturn(groups1) .thenReturn(groups2).thenReturn(groups2) .thenReturn(groups1).thenReturn(groups1) @@ -272,8 +260,8 @@ public class TestProviderBase extends ProviderSuper { prov.process(loadRequest(), this::handle); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java index 952a861d..ec79c03a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -55,13 +56,13 @@ import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.pap.main.notification.DeploymentStatus; +import org.onap.policy.pap.main.service.PolicyStatusService; public class TestSessionData extends ProviderSuper { private static final String GROUP_NAME = "groupA"; @@ -99,13 +100,13 @@ public class TestSessionData extends ProviderSuper { group1 = loadGroup("group1.json"); group2 = loadGroup("group2.json"); - session = new SessionData(dao, DEFAULT_USER); + session = new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService); } @Test public void testGetPolicyType() throws Exception { ToscaPolicyType policy1 = makePolicyType(POLICY_TYPE, POLICY_TYPE_VERSION); - when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1)); + when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1)); assertSame(policy1, session.getPolicyType(type)); @@ -115,7 +116,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicyType_NotFound() throws Exception { - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicyType(type)); } @@ -123,7 +124,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicyType_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); - when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex); + when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex); assertThatThrownBy(() -> session.getPolicyType(type)).isSameAs(ex); } @@ -131,7 +132,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_NullVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion(null); assertSame(policy1, session.getPolicy(ident)); @@ -143,13 +144,13 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_MajorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion("1"); assertSame(policy1, session.getPolicy(ident)); @@ -161,13 +162,13 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_MajorMinorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion(POLICY_VERSION); assertSame(policy1, session.getPolicy(ident)); @@ -179,12 +180,12 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_NotFound() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicy(ident)); } @@ -192,7 +193,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(ex); + when(toscaService.getFilteredPolicyList(any())).thenThrow(ex); assertThatThrownBy(() -> session.getPolicy(ident)).isSameAs(ex); } @@ -364,13 +365,13 @@ public class TestSessionData extends ProviderSuper { assertTrue(session.isUnchanged()); // force the groups into the cache - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); session.getActivePdpGroupsByPolicyType(type); /* * try group 1 */ - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); PdpGroup newgrp = new PdpGroup(group1); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -383,7 +384,7 @@ public class TestSessionData extends ProviderSuper { /* * try group 2 */ - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group2)); newgrp = new PdpGroup(group2); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -396,7 +397,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdate_NotInCache() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); assertThatIllegalStateException().isThrownBy(() -> session.update(new PdpGroup(group1))) .withMessage("group not cached: groupA"); @@ -404,49 +405,41 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetGroup() throws Exception { - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); - verify(dao).getPdpGroups(any()); + verify(pdpGroupService).getPdpGroups(any(String.class)); // repeat assertSame(group1, session.getGroup(GROUP_NAME)); // should not access dao again - verify(dao, times(1)).getPdpGroups(any()); + verify(pdpGroupService, times(1)).getPdpGroups(any(String.class)); } @Test public void testGetGroup_NotFound() throws Exception { - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Collections.emptyList()); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Collections.emptyList()); assertNull(session.getGroup(GROUP_NAME)); - verify(dao).getPdpGroups(any()); + verify(pdpGroupService).getPdpGroups(any(String.class)); // repeat assertNull(session.getGroup(GROUP_NAME)); // SHOULD access dao again - verify(dao, times(2)).getPdpGroups(GROUP_NAME); + verify(pdpGroupService, times(2)).getPdpGroups(GROUP_NAME); // find it this time - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); - verify(dao, times(3)).getPdpGroups(GROUP_NAME); - } - - @Test - public void testGetGroup_DaoEx() throws Exception { - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getPdpGroups(GROUP_NAME)).thenThrow(ex); - - assertThatThrownBy(() -> session.getGroup(GROUP_NAME)).isSameAs(ex); + verify(pdpGroupService, times(3)).getPdpGroups(GROUP_NAME); } @Test public void testGetActivePdpGroupsByPolicyType() throws Exception { List<PdpGroup> groups = Arrays.asList(group1, group2); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // repeat assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); @@ -454,32 +447,32 @@ public class TestSessionData extends ProviderSuper { assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); // only invoked once - should have used the cache for the rest - verify(dao, times(1)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(1)).getFilteredPdpGroups(any()); } @Test public void testAddGroup() throws Exception { List<PdpGroup> groups = Arrays.asList(group1, group2); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // query by each type assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); assertEquals(groups, session.getActivePdpGroupsByPolicyType(type2)); // invoked once for each type - verify(dao, times(2)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(2)).getFilteredPdpGroups(any()); // repeat - should be no more invocations assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); assertEquals(groups, session.getActivePdpGroupsByPolicyType(type2)); - verify(dao, times(2)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(2)).getFilteredPdpGroups(any()); } @Test public void testUpdateDb() throws Exception { // force the groups into the cache PdpGroup group3 = loadGroup("group3.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2, group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2, group3)); session.getActivePdpGroupsByPolicyType(type); // create groups 4 & 5 @@ -490,7 +483,7 @@ public class TestSessionData extends ProviderSuper { session.create(group5); // update group 1 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); PdpGroup newgrp1 = new PdpGroup(group1); session.update(newgrp1); @@ -499,12 +492,12 @@ public class TestSessionData extends ProviderSuper { session.update(newgrp1); // update group 3 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group3)); PdpGroup newgrp3 = new PdpGroup(group3); session.update(newgrp3); // update group 5 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group5)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group5)); PdpGroup newgrp5 = new PdpGroup(group5); session.update(newgrp5); @@ -529,22 +522,22 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdateDb_Empty() throws Exception { // force data into the cache - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); session.getActivePdpGroupsByPolicyType(type); PolicyNotification notif = new PolicyNotification(); session.updateDb(notif); assertThat(notif.getAdded()).isEmpty(); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); } @Test public void testDeleteGroupFromDb() throws Exception { session.deleteGroupFromDb(group1); - verify(dao).deletePdpGroup(group1.getName()); + verify(pdpGroupService).deletePdpGroup(group1.getName()); } @Test @@ -561,18 +554,19 @@ public class TestSessionData extends ProviderSuper { DeploymentStatus status = mock(DeploymentStatus.class); - session = new SessionData(dao, DEFAULT_USER) { - @Override - protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) { - return status; - } - }; + session = + new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService) { + @Override + protected DeploymentStatus makeDeploymentStatus(PolicyStatusService policyStatusService) { + return status; + } + }; ToscaPolicy policy = makePolicy(POLICY_NAME, POLICY_VERSION); policy.setType(POLICY_TYPE); policy.setTypeVersion(POLICY_TYPE_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy)); ToscaConceptIdentifier policyId = new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION); List<String> pdps = Arrays.asList(PDP1, PDP2); @@ -617,7 +611,7 @@ public class TestSessionData extends ProviderSuper { @SuppressWarnings("unchecked") ArgumentCaptor<ToscaTypedEntityFilter<ToscaPolicy>> captor = ArgumentCaptor.forClass(ToscaTypedEntityFilter.class); - verify(dao).getFilteredPolicyList(captor.capture()); + verify(toscaService).getFilteredPolicyList(captor.capture()); return captor.getValue(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index e51aa776..9c9f36ad 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,28 +27,32 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.Optional; import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.onap.policy.common.parameters.ValidationResult; 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.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.pap.main.PolicyPapRuntimeException; -import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PdpStatisticsService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.Yaml; public abstract class End2EndBase extends CommonPapRestServer { @@ -58,53 +62,24 @@ public abstract class End2EndBase extends CommonPapRestServer { private static final Yaml yaml = new Yaml(); /** - * DB connection. This is kept open until {@link #stop()} is invoked so that the in-memory DB is not destroyed. - */ - private static PolicyModelsProvider dbConn; - - /** - * DAO provider factory. - */ - private static PolicyModelsProviderFactoryWrapper daoFactory; - - /** * Context - should be initialized by setUp() method. */ protected End2EndContext context = null; + @Autowired + public PdpGroupService pdpGroupService; - /** - * Starts Main and connects to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - CommonPapRestServer.setUpBeforeClass(); - - final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class); - daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters()); - dbConn = daoFactory.create(); - } + @Autowired + public PdpStatisticsService pdpStatisticsService; - /** - * Tears down. - */ - @AfterClass - public static void tearDownAfterClass() { - try { - dbConn.close(); - } catch (final PfModelException e) { - logger.warn("failed to close the DB", e); - } + @Autowired + private ToscaServiceTemplateRepository serviceTemplateRepository; - try { - daoFactory.close(); - } catch (final Exception e) { - logger.warn("failed to close DAO factory", e); - } + @Autowired + public PolicyStatusService policyStatusService; - } + @Autowired + public ToscaServiceTemplateService toscaService; /** * Tears down. @@ -130,9 +105,10 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param yamlFile name of the YAML file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addToscaPolicyTypes(final String yamlFile) throws PfModelException { + public void addToscaPolicyTypes(final String yamlFile) throws PfModelException { final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class); - dbConn.createPolicyTypes(serviceTemplate); + JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate); + serviceTemplateRepository.save(jpaToscaServiceTemplate); } /** @@ -141,9 +117,30 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param yamlFile name of the YAML file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addToscaPolicies(final String yamlFile) throws PfModelException { + public void addToscaPolicies(final String yamlFile) throws PfModelException { final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class); - dbConn.createPolicies(serviceTemplate); + JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate); + serviceTemplateRepository.save(jpaToscaServiceTemplate); + } + + private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) { + JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate); + Optional<JpaToscaServiceTemplate> dbServiceTemplateOpt = serviceTemplateRepository + .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION)); + if (!dbServiceTemplateOpt.isEmpty()) { + JpaToscaServiceTemplate dbServiceTemplate = dbServiceTemplateOpt.get(); + if (dbServiceTemplate.getPolicyTypes() != null) { + jpaToscaServiceTemplate.setPolicyTypes(dbServiceTemplate.getPolicyTypes()); + } + if (dbServiceTemplate.getDataTypes() != null) { + jpaToscaServiceTemplate.setDataTypes(dbServiceTemplate.getDataTypes()); + } + if (dbServiceTemplate.getTopologyTemplate() != null) { + jpaToscaServiceTemplate.setTopologyTemplate(dbServiceTemplate.getTopologyTemplate()); + } + } + + return jpaToscaServiceTemplate; } /** @@ -152,7 +149,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param jsonFile name of the JSON file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addGroups(final String jsonFile) throws PfModelException { + public void addGroups(final String jsonFile) throws PfModelException { final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class); final ValidationResult result = groups.validatePapRest(); @@ -160,7 +157,7 @@ public abstract class End2EndBase extends CommonPapRestServer { throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult()); } - dbConn.createPdpGroups(groups.getGroups()); + pdpGroupService.createPdpGroups(groups.getGroups()); } /** @@ -169,8 +166,8 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param name name of the pdpGroup * @throws PfModelException if a DAO error occurs */ - public static List<PdpGroup> fetchGroups(final String name) throws PfModelException { - return dbConn.getPdpGroups(name); + public List<PdpGroup> fetchGroups(final String name) throws PfModelException { + return pdpGroupService.getPdpGroups(name); } /** @@ -181,10 +178,9 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param subGroupName name of the pdpSubGroup * @throws PfModelException if a DAO error occurs */ - public static List<PdpStatistics> fetchPdpStatistics(final String instanceId, final String groupName, - final String subGroupName) throws PfModelException { - return dbConn.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(instanceId).group(groupName).subGroup(subGroupName).build()); + public Map<String, Map<String, List<PdpStatistics>>> fetchPdpStatistics(final String instanceId, + final String groupName, final String subGroupName) throws PfModelException { + return pdpStatisticsService.fetchDatabaseStatistics(groupName, subGroupName, instanceId, 100, null, null); } /** @@ -193,9 +189,9 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param jsonFile name of the JSON file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addPdpPolicyStatus(final String jsonFile) throws PfModelException { + public void addPdpPolicyStatus(final String jsonFile) throws PfModelException { final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class); - dbConn.cudPolicyStatus(data.records, null, null); + policyStatusService.cudPolicyStatus(data.records, null, null); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java index dacee672..3f763863 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -31,7 +32,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.junit.After; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.models.pap.concepts.PdpGroupUpdateResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; @@ -49,23 +49,12 @@ public class PdpGroupCreateOrUpdateTest extends End2EndBase { private static final String GROUP_ENDPOINT = "pdps"; /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - } - - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java index 9b80bb7e..e3ad0044 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -33,7 +33,6 @@ import java.util.concurrent.TimeUnit; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; @@ -52,24 +51,13 @@ public class PdpGroupDeleteTest extends End2EndBase { private static final String DELETE_POLICIES_ENDPOINT = "pdps/policies"; /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java index 08974ed8..cdb1fa9d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -36,7 +36,6 @@ import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; @@ -59,24 +58,13 @@ public class PdpGroupDeployTest extends End2EndBase { private static final String DEPLOY_SUBGROUP = "pdpTypeA"; /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java index a0a40ce5..d6472ce1 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -32,7 +33,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; @@ -46,18 +47,19 @@ public class PdpGroupQueryTest extends End2EndBase { private static final String GROUP_ENDPOINT = "pdps"; /** - * Starts Main and adds policies to the DB. + * Sets up. * - * @throws Exception if an error occurs + * @throws Exception the exception */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); + @Override + @Before + public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); addToscaPolicies("monitoring.policy.yaml"); addGroups("queryGroup.json"); + super.setUp(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java index df7fcc01..2fa7cfb4 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. 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. @@ -30,7 +31,6 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.models.pap.concepts.PdpGroupStateChangeResponse; import org.onap.policy.models.pdp.concepts.PdpStatus; @@ -47,24 +47,13 @@ public class PdpGroupStateChangeTest extends End2EndBase { private static final String GROUP_ENDPOINT = "pdps/groups"; /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java index d98a4ba3..b0a135d2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. + * Copyright (C) 2021-2022 Bell Canada. 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. @@ -26,18 +26,17 @@ import java.util.List; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; +import org.junit.After; 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.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.repository.PolicyAuditRepository; import org.onap.policy.pap.main.rest.PolicyAuditControllerV1; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.springframework.beans.factory.annotation.Autowired; public class PolicyAuditTest extends End2EndBase { private static final String TEST_GROUP = "testGroup"; @@ -54,6 +53,12 @@ public class PolicyAuditTest extends End2EndBase { private static int BAD_REQUEST_STATUS_CODE = 400; private static final String BAD_REQUEST_MSG = "NumberFormatException For"; + @Autowired + private PolicyAuditService policyAuditService; + + @Autowired + private PolicyAuditRepository policyAuditRepository; + @Override @Before public void setUp() throws Exception { @@ -61,23 +66,31 @@ public class PolicyAuditTest extends End2EndBase { setupEnv(); } + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + policyAuditRepository.deleteAll(); + super.tearDown(); + } + private void setupEnv() { List<PolicyAudit> recordList = new ArrayList<>(); Instant auditRecordTime = Instant.ofEpochSecond(1627392315L); - PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) + try { + PolicyAudit audit1 = PolicyAudit.builder().pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) .policy(POLICY_A).action(AuditAction.DEPLOYMENT) .timestamp(auditRecordTime).user(DEFAULT_USER).build(); - PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) + PolicyAudit audit2 = PolicyAudit.builder().pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT) .timestamp(auditRecordTime).user(DEFAULT_USER).build(); recordList.add(audit1); recordList.add(audit2); - databaseProvider.createAuditRecords(recordList); - } catch (final PfModelException exp) { + policyAuditService.createAuditRecords(recordList); + } catch (Exception exp) { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, exp.getMessage()); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java index b44d4af7..121318f5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -28,7 +28,7 @@ import java.util.List; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -41,15 +41,11 @@ public class PolicyStatusTest extends End2EndBase { private static final String POLICY_STATUS_ENDPOINT = "policies/deployed"; private static final String POLICY_DEPLOYMENT_STATUS_ENDPOINT = "policies/status"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); + @Override + @Before + public void setUp() throws Exception { addPdpPolicyStatus("policyStatus.json"); + super.setUp(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java index 1331e458..876ea0fb 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -32,17 +32,12 @@ import java.util.Map; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.parameters.CommonTestData; -import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.rest.PapStatisticsManager; import org.onap.policy.pap.main.rest.StatisticsReport; @@ -52,6 +47,7 @@ public class StatisticsTest extends End2EndBase { private static final String START_TIME_NAME = "startTime"; private static final long TIMESTAMP_SEC = 1562494272; + private static PdpStatistics pdpStatisticsRecord; /** * Adds a record to the DB. @@ -60,25 +56,24 @@ public class StatisticsTest extends End2EndBase { public static void setUpBeforeClass() throws Exception { End2EndBase.setUpBeforeClass(); - PolicyModelsProviderFactory modelProviderWrapper = new PolicyModelsProviderFactory(); - PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); - try (PolicyModelsProvider databaseProvider = - modelProviderWrapper.createPolicyModelsProvider(parameterGroup.getDatabaseProviderParameters())) { - PdpStatistics pdpStatisticsRecord = new PdpStatistics(); - pdpStatisticsRecord.setPdpGroupName("defaultGroup"); - pdpStatisticsRecord.setPdpSubGroupName("apex"); - pdpStatisticsRecord.setPdpInstanceId("pdp1"); - pdpStatisticsRecord.setTimeStamp(Instant.ofEpochSecond(TIMESTAMP_SEC)); - pdpStatisticsRecord.setPolicyDeployCount(1); - pdpStatisticsRecord.setPolicyDeployFailCount(0); - pdpStatisticsRecord.setPolicyDeploySuccessCount(1); - pdpStatisticsRecord.setPolicyExecutedCount(1); - pdpStatisticsRecord.setPolicyExecutedFailCount(0); - pdpStatisticsRecord.setPolicyExecutedSuccessCount(1); - databaseProvider.createPdpStatistics(List.of(pdpStatisticsRecord)); - } catch (final PfModelException exp) { - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, exp.getMessage()); - } + pdpStatisticsRecord = new PdpStatistics(); + pdpStatisticsRecord.setPdpGroupName("defaultGroup"); + pdpStatisticsRecord.setPdpSubGroupName("apex"); + pdpStatisticsRecord.setPdpInstanceId("pdp1"); + pdpStatisticsRecord.setTimeStamp(Instant.ofEpochSecond(TIMESTAMP_SEC)); + pdpStatisticsRecord.setPolicyDeployCount(1); + pdpStatisticsRecord.setPolicyDeployFailCount(0); + pdpStatisticsRecord.setPolicyDeploySuccessCount(1); + pdpStatisticsRecord.setPolicyExecutedCount(1); + pdpStatisticsRecord.setPolicyExecutedFailCount(0); + pdpStatisticsRecord.setPolicyExecutedSuccessCount(1); + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + pdpStatisticsService.createPdpStatistics(List.of(pdpStatisticsRecord)); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java index e7090fcf..549eb96b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java @@ -71,7 +71,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { public void setUp() throws Exception { super.setUp(); PdpGroups defaultGroup = coder.decode(ResourceUtils.getResourceAsString("e2e/PdpGroups.json"), PdpGroups.class); - pdpGroupService.savePdpGroups(defaultGroup.getGroups()); + pdpGroupService.createPdpGroups(defaultGroup.getGroups()); groupsToCreate = coder.decode(ResourceUtils.getResourceAsString("e2e/createGroups.json"), PdpGroups.class); } @@ -82,23 +82,23 @@ public class PdpGroupServiceTest extends CommonPapRestServer { assertThat(pdpGroups).hasSize(1); assertThat(pdpGroups.get(0).getName()).isEqualTo(DEFAULT_GROUP); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - pdpGroups = pdpGroupService.getPdpGroupByName(CREATE_GROUPS); + pdpGroups = pdpGroupService.getPdpGroups(CREATE_GROUPS); assertThat(pdpGroups).hasSize(1); assertThat(pdpGroups.get(0).getName()).isEqualTo(CREATE_GROUPS); - assertThat(pdpGroupService.getPdpGroupByState(PdpState.PASSIVE)).isEqualTo(pdpGroups); + assertThat(pdpGroupService.getPdpGroups(PdpState.PASSIVE)).isEqualTo(pdpGroups); - List<PdpGroup> activePdpGroups = pdpGroupService.getPdpGroupByState(PdpState.ACTIVE); + List<PdpGroup> activePdpGroups = pdpGroupService.getPdpGroups(PdpState.ACTIVE); assertThat(activePdpGroups).hasSize(1); assertThat(activePdpGroups.get(0).getPdpSubgroups()).hasSize(3); - assertThat(pdpGroupService.getPdpGroupByNameAndState(CREATE_GROUPS, PdpState.PASSIVE)).hasSize(1); - assertThat(pdpGroupService.getPdpGroupByNameAndState("invalid-group", PdpState.PASSIVE)).hasSize(0); - assertThat(pdpGroupService.getPdpGroupByNameAndState(DEFAULT_GROUP, PdpState.ACTIVE)).hasSize(1); + assertThat(pdpGroupService.getPdpGroups(CREATE_GROUPS, PdpState.PASSIVE)).hasSize(1); + assertThat(pdpGroupService.getPdpGroups("invalid-group", PdpState.PASSIVE)).hasSize(0); + assertThat(pdpGroupService.getPdpGroups(DEFAULT_GROUP, PdpState.ACTIVE)).hasSize(1); PdpGroupFilter filter = PdpGroupFilter.builder() .policyTypeList( @@ -116,20 +116,21 @@ public class PdpGroupServiceTest extends CommonPapRestServer { @Test public void testPdpGroupsCrudFailure() { - assertThatThrownBy(() -> pdpGroupService.getPdpGroupByState(null)) + PdpState pdpState = null; + assertThatThrownBy(() -> pdpGroupService.getPdpGroups(pdpState)) .hasMessage(String.format(FIELD_IS_NULL, "pdpState")); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThatThrownBy(() -> pdpGroupService.deletePdpGroup("invalid-group")) .hasMessage("delete of PDP group \"invalid-group\" failed, PDP group does not exist"); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - assertThatThrownBy(() -> pdpGroupService.savePdpGroups(null)) + assertThatThrownBy(() -> pdpGroupService.createPdpGroups(null)) .hasMessage(String.format(FIELD_IS_NULL, "pdpGroups")); PdpGroup invalidPdpGroup = new PdpGroup(groupsToCreate.getGroups().get(0)); invalidPdpGroup.setName("invalidPdpGroup"); invalidPdpGroup.setPdpGroupState(null); - assertThatThrownBy(() -> pdpGroupService.savePdpGroups(List.of(invalidPdpGroup))) + assertThatThrownBy(() -> pdpGroupService.createPdpGroups(List.of(invalidPdpGroup))) .hasMessageContaining("Failed saving PdpGroup.") .hasMessageContaining("item \"pdpGroupState\" value \"null\" INVALID, is null"); pdpGroupService.deletePdpGroup(CREATE_GROUPS); @@ -154,16 +155,16 @@ public class PdpGroupServiceTest extends CommonPapRestServer { pdpGroupService.updatePdp(NAME, TYPE, new Pdp()); }).hasMessage(LOCALNAME_IS_NULL); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - PdpGroup pdpGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup pdpGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); Pdp pdp = pdpGroup.getPdpSubgroups().get(0).getPdpInstances().get(0); assertThat(pdp.getHealthy()).isEqualTo(PdpHealthStatus.HEALTHY); // now update and test pdp.setHealthy(PdpHealthStatus.NOT_HEALTHY); pdpGroupService.updatePdp(CREATE_GROUPS, "pdpTypeA", pdp); - PdpGroup updatGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup updatGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); assertThat(updatGroup.getPdpSubgroups().get(0).getPdpInstances().get(0).getHealthy()) .isEqualTo(PdpHealthStatus.NOT_HEALTHY); pdpGroupService.deletePdpGroup(CREATE_GROUPS); @@ -183,16 +184,16 @@ public class PdpGroupServiceTest extends CommonPapRestServer { pdpGroupService.updatePdpSubGroup(NAME, new PdpSubGroup()); }).hasMessage(LOCALNAME_IS_NULL); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - PdpGroup pdpGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup pdpGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); PdpSubGroup pdpSubGroup = pdpGroup.getPdpSubgroups().get(0); assertThat(pdpSubGroup.getDesiredInstanceCount()).isEqualTo(2); // now update and test pdpSubGroup.setDesiredInstanceCount(1); pdpGroupService.updatePdpSubGroup(CREATE_GROUPS, pdpSubGroup); - PdpGroup updatGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup updatGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); assertThat(updatGroup.getPdpSubgroups().get(0).getDesiredInstanceCount()).isEqualTo(1); pdpGroupService.deletePdpGroup(CREATE_GROUPS); } diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java index 86fd9b04..fc604cee 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java @@ -27,10 +27,12 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onap.policy.models.base.Validated; import org.onap.policy.models.pdp.concepts.PdpStatistics; +import org.onap.policy.pap.main.repository.PdpStatisticsRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.beans.factory.annotation.Autowired; @@ -49,6 +51,9 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { @Autowired private PdpStatisticsService pdpStatisticsService; + @Autowired + private PdpStatisticsRepository pdpStatisticsRepository; + private PdpStatistics pdpStatistics1; private PdpStatistics pdpStatistics2; private PdpStatistics pdpStatistics3; @@ -63,10 +68,19 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { @Before public void setUp() throws Exception { super.setUp(); - pdpStatistics1 = generatePdpStatistics(NAME1, TIMESTAMP1, 1L, GROUP, SUBGROUP); - pdpStatistics2 = generatePdpStatistics("name2", TIMESTAMP1, 2L, GROUP, SUBGROUP); - pdpStatistics3 = generatePdpStatistics(NAME1, TIMESTAMP2, 3L, GROUP, SUBGROUP); - pdpStatistics4 = generatePdpStatistics(NAME3, TIMESTAMP2, 4L, GROUP0, SUBGROUP); + pdpStatistics1 = generatePdpStatistics(NAME1, TIMESTAMP1, GROUP, SUBGROUP); + pdpStatistics2 = generatePdpStatistics("name2", TIMESTAMP1, GROUP, SUBGROUP); + pdpStatistics3 = generatePdpStatistics(NAME1, TIMESTAMP2, GROUP, SUBGROUP); + pdpStatistics4 = generatePdpStatistics(NAME3, TIMESTAMP2, GROUP0, SUBGROUP); + } + + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + pdpStatisticsRepository.deleteAll(); } @Test @@ -167,12 +181,11 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { assertThat(created.get(GROUP0).get(SUBGROUP)).isEqualTo(List.of(pdpStatistics4)); } - private PdpStatistics generatePdpStatistics(String pdpInstanceId, Instant date, Long id, String group, + private PdpStatistics generatePdpStatistics(String pdpInstanceId, Instant date, String group, String subgroup) { PdpStatistics pdpStatistics11 = new PdpStatistics(); pdpStatistics11.setPdpInstanceId(pdpInstanceId); pdpStatistics11.setTimeStamp(date); - pdpStatistics11.setGeneratedId(id); pdpStatistics11.setPdpGroupName(group); pdpStatistics11.setPdpSubGroupName(subgroup); pdpStatistics11.setPolicyDeployCount(2); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java index 980cdd1a..68044ad7 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java @@ -27,11 +27,13 @@ import static org.junit.Assert.assertThrows; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; +import org.junit.After; import org.junit.Test; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.pap.main.repository.PolicyAuditRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.beans.factory.annotation.Autowired; @@ -47,6 +49,18 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { @Autowired private PolicyAuditService policyAuditService; + @Autowired + private PolicyAuditRepository policyAuditRepository; + + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + policyAuditRepository.deleteAll(); + } + @Test public void testCreateAuditRecordsSuccess() { policyAuditService.createAuditRecords(generatePolicyAudits(Instant.now(), GROUP_A, MY_POLICY)); @@ -109,10 +123,10 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { } private List<PolicyAudit> generatePolicyAudits(Instant date, String group, ToscaConceptIdentifier policy) { - PolicyAudit deploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy).auditId(1L) + PolicyAudit deploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy) .action(AuditAction.DEPLOYMENT).timestamp(date.truncatedTo(ChronoUnit.SECONDS)).build(); - PolicyAudit undeploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy).auditId(2L) + PolicyAudit undeploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy) .action(AuditAction.UNDEPLOYMENT).timestamp(date.plusSeconds(1).truncatedTo(ChronoUnit.SECONDS)).build(); return List.of(deploy, undeploy); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 1a1415a5..2204392a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. 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. @@ -41,6 +41,7 @@ import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.comm.PdpHeartbeatListener; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.CommonTestData; @@ -91,7 +92,9 @@ public class TestPapActivator { final PapParameterGroup parGroup = new CommonTestData().getPapParameterGroup(6969); - activator = new PapActivator(parGroup); + activator = new PapActivator(parGroup, new PolicyNotifier(null), new PdpHeartbeatListener(), + new PdpModifyRequestMap(null, null, null, null, null)); + } /** @@ -118,7 +121,6 @@ public class TestPapActivator { assertNotNull(Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class)); assertNotNull(Registry.get(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class)); assertNotNull(Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class)); - assertNotNull(Registry.get(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class)); // repeat - should throw an exception assertThatIllegalStateException().isThrownBy(() -> activator.start()); @@ -136,7 +138,6 @@ public class TestPapActivator { assertNull(Registry.getOrDefault(PapConstants.REG_PDP_MODIFY_LOCK, Object.class, null)); assertNull(Registry.getOrDefault(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class, null)); assertNull(Registry.getOrDefault(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class, null)); - assertNull(Registry.getOrDefault(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class, null)); // repeat - should throw an exception assertThatIllegalStateException().isThrownBy(() -> activator.stop()); |