Java 17 / Spring 6 / Spring Boot 3 Upgrade
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / TestPdpGroupDeleteProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2020-2023 Nordix Foundation.
7  * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import static org.assertj.core.api.Assertions.assertThatThrownBy;
26 import static org.junit.jupiter.api.Assertions.assertEquals;
27 import static org.junit.jupiter.api.Assertions.assertFalse;
28 import static org.junit.jupiter.api.Assertions.assertSame;
29 import static org.junit.jupiter.api.Assertions.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.ArgumentMatchers.eq;
32 import static org.mockito.Mockito.doThrow;
33 import static org.mockito.Mockito.never;
34 import static org.mockito.Mockito.spy;
35 import static org.mockito.Mockito.verify;
36 import static org.mockito.Mockito.when;
37
38 import jakarta.ws.rs.core.Response.Status;
39 import java.util.List;
40 import java.util.Set;
41 import org.junit.jupiter.api.AfterAll;
42 import org.junit.jupiter.api.BeforeEach;
43 import org.junit.jupiter.api.Test;
44 import org.mockito.ArgumentCaptor;
45 import org.mockito.Captor;
46 import org.mockito.Mock;
47 import org.onap.policy.common.utils.services.Registry;
48 import org.onap.policy.models.base.PfModelException;
49 import org.onap.policy.models.base.PfModelRuntimeException;
50 import org.onap.policy.models.pdp.concepts.PdpGroup;
51 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
52 import org.onap.policy.models.pdp.concepts.PdpUpdate;
53 import org.onap.policy.models.pdp.enums.PdpState;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
56 import org.onap.policy.pap.main.rest.ProviderBase.Updater;
57
58 public class TestPdpGroupDeleteProvider extends ProviderSuper {
59     private static final String EXPECTED_EXCEPTION = "expected exception";
60     private static final String GROUP1_NAME = "groupA";
61
62     @Mock
63     private SessionData session;
64
65     @Captor
66     private ArgumentCaptor<Set<String>> pdpCaptor;
67
68     private MyProvider prov;
69     private ToscaConceptIdentifierOptVersion optIdent;
70     private ToscaConceptIdentifierOptVersion fullIdent;
71     private ToscaConceptIdentifier ident;
72     private Updater updater;
73
74     @AfterAll
75     public static void tearDownAfterClass() {
76         Registry.newRegistry();
77     }
78
79     /**
80      * Configures mocks and objects.
81      *
82      * @throws Exception if an error occurs
83      */
84     @BeforeEach
85     @Override
86     public void setUp() throws Exception {
87         super.setUp();
88         prov = new MyProvider();
89         super.initialize(prov);
90
91         ident = policy1.getIdentifier();
92         optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null);
93         fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion());
94
95         updater = prov.makeUpdater(session, policy1, fullIdent);
96     }
97
98     @Test
99     void testDeleteGroup_Active() throws Exception {
100         PdpGroup group = loadGroup("deleteGroup.json");
101
102         group.setPdpGroupState(PdpState.ACTIVE);
103
104         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
105
106         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
107             .hasMessage("group is still ACTIVE");
108     }
109
110     @Test
111     void testDeleteGroup_NotFound() {
112         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
113             .hasMessage("group not found")
114             .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
115             .isEqualTo(Status.NOT_FOUND);
116     }
117
118     @Test
119     void testDeleteGroup_Inactive() throws Exception {
120         PdpGroup group = loadGroup("deleteGroup.json");
121
122         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
123
124         prov.deleteGroup(GROUP1_NAME);
125
126         verify(session).deleteGroupFromDb(group);
127
128         // should have done no requests for the PDPs
129         verify(session, never()).addRequests(any(), any());
130     }
131
132     @Test
133     void testDeleteGroup_Ex() throws Exception {
134         PdpGroup group = loadGroup("deleteGroup.json");
135
136         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
137
138         PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
139         doThrow(ex).when(session).deleteGroupFromDb(group);
140
141         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
142     }
143
144     /**
145      * Tests using a real provider, just to verify end-to-end functionality.
146      *
147      * @throws Exception if an error occurs
148      */
149     @Test
150     void testUndeploy_Full() throws Exception {
151         when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1));
152
153         PdpGroup group = loadGroup("undeploy.json");
154
155         when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group));
156         when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1));
157
158         PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider();
159         super.initialize(deleteProvider);
160         deleteProvider.undeploy(fullIdent, DEFAULT_USER);
161
162         // should have updated the old group
163         List<PdpGroup> updates = getGroupUpdates();
164         assertEquals(1, updates.size());
165         assertSame(group, updates.get(0));
166         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
167
168         // should be one less item in the new subgroup
169         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
170
171         // should have updated the PDPs
172         List<PdpUpdate> requests = getUpdateRequests(1);
173         assertEquals(1, requests.size());
174         PdpUpdate req = requests.get(0);
175         assertEquals("pdpA", req.getName());
176         assertEquals(GROUP1_NAME, req.getPdpGroup());
177         assertEquals("pdpTypeA", req.getPdpSubgroup());
178         assertEquals(List.of(policy1.getIdentifier()), req.getPoliciesToBeUndeployed());
179     }
180
181     @Test
182     void testUndeployPolicy_NotFound() {
183         when(session.isUnchanged()).thenReturn(true);
184
185         assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class)
186             .hasMessage("policy does not appear in any PDP group: policyA null");
187     }
188
189     @Test
190     void testUndeployPolicy_DaoEx() throws Exception {
191         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
192
193         prov = spy(prov);
194         doThrow(exc).when(prov).processPolicy(any(), any());
195
196         assertThatThrownBy(() -> prov.undeploy(optIdent, null)).isSameAs(exc);
197     }
198
199     @Test
200     void testUndeployPolicy_RtEx() throws Exception {
201         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
202
203         prov = spy(prov);
204         doThrow(exc).when(prov).processPolicy(any(), any());
205
206         // process method catches RuntimeException and re-throws as PfModelException
207         assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class)
208             .hasRootCauseMessage(EXPECTED_EXCEPTION);
209     }
210
211     @Test
212     void testMakeUpdater_WithVersion() throws PfModelException {
213         /*
214          * this group has two matching policies and one policy with a different name.
215          */
216         PdpGroup group = loadGroup("undeploy.json");
217
218         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
219         int origSize = subgroup.getPolicies().size();
220
221         // invoke updater - matching both name and version
222         assertTrue(updater.apply(group, subgroup));
223
224         // identified policy should have been removed
225         assertEquals(origSize - 1, subgroup.getPolicies().size());
226         assertFalse(subgroup.getPolicies().contains(ident));
227
228         verify(session).trackUndeploy(eq(ident), pdpCaptor.capture(), eq(group.getName()), eq(subgroup.getPdpType()));
229         assertEquals("[pdpA]", pdpCaptor.getValue().toString());
230     }
231
232     @Test
233     void testMakeUpdater_NullVersion() throws PfModelException {
234         /*
235          * this group has two matching policies and one policy with a different name.
236          */
237         PdpGroup group = loadGroup("undeploy.json");
238
239         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
240         int origSize = subgroup.getPolicies().size();
241
242         // invoke updater - matching the name, but with a null (i.e., wild-card) version
243         updater = prov.makeUpdater(session, policy1, optIdent);
244         assertTrue(updater.apply(group, subgroup));
245
246         // identified policy should have been removed
247         assertEquals(origSize - 2, subgroup.getPolicies().size());
248         assertFalse(subgroup.getPolicies().contains(ident));
249     }
250
251     @Test
252     void testMakeUpdater_NotFound() throws PfModelException {
253         /*
254          * this group has one policy with a different name and one with a different
255          * version, but not the policy of interest.
256          */
257         PdpGroup group = loadGroup("undeployMakeUpdaterGroupNotFound.json");
258
259         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
260         int origSize = subgroup.getPolicies().size();
261
262         // invoke updater
263         assertFalse(updater.apply(group, subgroup));
264
265         // should be unchanged
266         assertEquals(origSize, subgroup.getPolicies().size());
267     }
268
269     private class MyProvider extends PdpGroupDeleteProvider {
270
271         private MyProvider() {
272             super.initialize();
273         }
274
275         @Override
276         protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
277             processor.accept(session, request);
278         }
279
280         @Override
281         protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
282             throws PfModelException {
283             // do nothing
284         }
285     }
286 }