Move PAP database provider to spring boot default
[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-2021 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.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.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 java.util.Arrays;
39 import java.util.List;
40 import java.util.Set;
41 import javax.ws.rs.core.Response.Status;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.Captor;
47 import org.mockito.Mock;
48 import org.onap.policy.common.utils.services.Registry;
49 import org.onap.policy.models.base.PfModelException;
50 import org.onap.policy.models.base.PfModelRuntimeException;
51 import org.onap.policy.models.pdp.concepts.PdpGroup;
52 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
53 import org.onap.policy.models.pdp.concepts.PdpUpdate;
54 import org.onap.policy.models.pdp.enums.PdpState;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
57 import org.onap.policy.pap.main.rest.ProviderBase.Updater;
58
59 public class TestPdpGroupDeleteProvider extends ProviderSuper {
60     private static final String EXPECTED_EXCEPTION = "expected exception";
61     private static final String GROUP1_NAME = "groupA";
62
63     @Mock
64     private SessionData session;
65
66     @Captor
67     private ArgumentCaptor<Set<String>> pdpCaptor;
68
69     private MyProvider prov;
70     private ToscaConceptIdentifierOptVersion optIdent;
71     private ToscaConceptIdentifierOptVersion fullIdent;
72     private ToscaConceptIdentifier ident;
73     private Updater updater;
74
75     @AfterClass
76     public static void tearDownAfterClass() {
77         Registry.newRegistry();
78     }
79
80     /**
81      * Configures mocks and objects.
82      *
83      * @throws Exception if an error occurs
84      */
85     @Before
86     @Override
87     public void setUp() throws Exception {
88         super.setUp();
89         prov = new MyProvider();
90         super.initialize(prov);
91
92         ident = policy1.getIdentifier();
93         optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null);
94         fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion());
95
96         updater = prov.makeUpdater(session, policy1, fullIdent);
97     }
98
99     @Test
100     public void testDeleteGroup_Inctive() throws Exception {
101         PdpGroup group = loadGroup("deleteGroup.json");
102
103         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
104
105         prov.deleteGroup(GROUP1_NAME);
106
107         verify(session).deleteGroupFromDb(group);
108
109         // should be no PDP requests
110         verify(session, never()).addRequests(any(), any());
111     }
112
113     @Test
114     public void testDeleteGroup_Active() throws Exception {
115         PdpGroup group = loadGroup("deleteGroup.json");
116
117         group.setPdpGroupState(PdpState.ACTIVE);
118
119         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
120
121         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
122                 .hasMessage("group is still ACTIVE");
123     }
124
125     @Test
126     public void testDeleteGroup_NotFound() throws Exception {
127         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
128                 .hasMessage("group not found")
129                 .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
130                 .isEqualTo(Status.NOT_FOUND);
131     }
132
133     @Test
134     public void testDeleteGroup_Inactive() throws Exception {
135         PdpGroup group = loadGroup("deleteGroup.json");
136
137         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
138
139         prov.deleteGroup(GROUP1_NAME);
140
141         verify(session).deleteGroupFromDb(group);
142
143         // should done no requests for the PDPs
144         verify(session, never()).addRequests(any(), any());
145     }
146
147     @Test
148     public void testDeleteGroup_Ex() throws Exception {
149         PdpGroup group = loadGroup("deleteGroup.json");
150
151         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
152
153         PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
154         doThrow(ex).when(session).deleteGroupFromDb(group);
155
156         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
157     }
158
159     /**
160      * Tests using a real provider, just to verify end-to-end functionality.
161      *
162      * @throws Exception if an error occurs
163      */
164     @Test
165     public void testUndeploy_Full() throws Exception {
166         when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
167
168         PdpGroup group = loadGroup("undeploy.json");
169
170         when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group));
171         when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
172
173         PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider();
174         super.initialize(deleteProvider);
175         deleteProvider.undeploy(fullIdent, DEFAULT_USER);
176
177         // should have updated the old group
178         List<PdpGroup> updates = getGroupUpdates();
179         assertEquals(1, updates.size());
180         assertSame(group, updates.get(0));
181         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
182
183         // should be one less item in the new subgroup
184         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
185
186         // should have updated the PDPs
187         List<PdpUpdate> requests = getUpdateRequests(1);
188         assertEquals(1, requests.size());
189         PdpUpdate req = requests.get(0);
190         assertEquals("pdpA", req.getName());
191         assertEquals(GROUP1_NAME, req.getPdpGroup());
192         assertEquals("pdpTypeA", req.getPdpSubgroup());
193         assertEquals(Arrays.asList(policy1.getIdentifier()), req.getPoliciesToBeUndeployed());
194     }
195
196     @Test
197     public void testUndeployPolicy_NotFound() throws Exception {
198         when(session.isUnchanged()).thenReturn(true);
199
200         assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class)
201                 .hasMessage("policy does not appear in any PDP group: policyA null");
202     }
203
204     @Test
205     public void testUndeployPolicy_DaoEx() throws Exception {
206         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
207
208         prov = spy(prov);
209         doThrow(exc).when(prov).processPolicy(any(), any());
210
211         assertThatThrownBy(() -> prov.undeploy(optIdent, null)).isSameAs(exc);
212     }
213
214     @Test
215     public void testUndeployPolicy_RtEx() throws Exception {
216         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
217
218         prov = spy(prov);
219         doThrow(exc).when(prov).processPolicy(any(), any());
220
221         // process method catches RuntimeException and re-throws as PfModelException
222         assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class)
223                 .hasRootCauseMessage(EXPECTED_EXCEPTION);
224     }
225
226     @Test
227     public void testMakeUpdater_WithVersion() throws PfModelException {
228         /*
229          * this group has two matching policies and one policy with a different name.
230          */
231         PdpGroup group = loadGroup("undeploy.json");
232
233         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
234         int origSize = subgroup.getPolicies().size();
235
236         // invoke updater - matching both name and version
237         assertTrue(updater.apply(group, subgroup));
238
239         // identified policy should have been removed
240         assertEquals(origSize - 1, subgroup.getPolicies().size());
241         assertFalse(subgroup.getPolicies().contains(ident));
242
243         verify(session).trackUndeploy(eq(ident), pdpCaptor.capture(), eq(group.getName()), eq(subgroup.getPdpType()));
244         assertEquals("[pdpA]", pdpCaptor.getValue().toString());
245     }
246
247     @Test
248     public void testMakeUpdater_NullVersion() throws PfModelException {
249         /*
250          * this group has two matching policies and one policy with a different name.
251          */
252         PdpGroup group = loadGroup("undeploy.json");
253
254         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
255         int origSize = subgroup.getPolicies().size();
256
257         // invoke updater - matching the name, but with a null (i.e., wild-card) version
258         updater = prov.makeUpdater(session, policy1, optIdent);
259         assertTrue(updater.apply(group, subgroup));
260
261         // identified policy should have been removed
262         assertEquals(origSize - 2, subgroup.getPolicies().size());
263         assertFalse(subgroup.getPolicies().contains(ident));
264     }
265
266     @Test
267     public void testMakeUpdater_NotFound() throws PfModelException {
268         /*
269          * this group has one policy with a different name and one with a different
270          * version, but not the policy of interest.
271          */
272         PdpGroup group = loadGroup("undeployMakeUpdaterGroupNotFound.json");
273
274         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
275         int origSize = subgroup.getPolicies().size();
276
277         // invoke updater
278         assertFalse(updater.apply(group, subgroup));
279
280         // should be unchanged
281         assertEquals(origSize, subgroup.getPolicies().size());
282     }
283
284     private class MyProvider extends PdpGroupDeleteProvider {
285         private MyProvider() {
286             super.initialize();
287         }
288
289         @Override
290         protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
291             processor.accept(session, request);
292         }
293
294         @Override
295         protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
296                 throws PfModelException {
297             // do nothing
298         }
299     }
300 }