Migrate pap startup & controllers to spring boot
[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 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.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     @AfterClass
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     @Before
85     @Override
86     public void setUp() throws Exception {
87
88         super.setUp();
89
90         ident = policy1.getIdentifier();
91         optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null);
92         fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion());
93
94         prov = new MyProvider();
95         updater = prov.makeUpdater(session, policy1, fullIdent);
96     }
97
98     @Test
99     public void testDeleteGroup_Inctive() throws Exception {
100         PdpGroup group = loadGroup("deleteGroup.json");
101
102         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
103
104         prov.deleteGroup(GROUP1_NAME);
105
106         verify(session).deleteGroupFromDb(group);
107
108         // should be no PDP requests
109         verify(session, never()).addRequests(any(), any());
110     }
111
112     @Test
113     public void testDeleteGroup_Active() throws Exception {
114         PdpGroup group = loadGroup("deleteGroup.json");
115
116         group.setPdpGroupState(PdpState.ACTIVE);
117
118         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
119
120         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
121                 .hasMessage("group is still ACTIVE");
122     }
123
124     @Test
125     public void testDeleteGroup_NotFound() throws Exception {
126         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
127                 .hasMessage("group not found")
128                 .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
129                 .isEqualTo(Status.NOT_FOUND);
130     }
131
132     @Test
133     public void testDeleteGroup_Inactive() throws Exception {
134         PdpGroup group = loadGroup("deleteGroup.json");
135
136         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
137
138         prov.deleteGroup(GROUP1_NAME);
139
140         verify(session).deleteGroupFromDb(group);
141
142         // should done no requests for the PDPs
143         verify(session, never()).addRequests(any(), any());
144     }
145
146     @Test
147     public void testDeleteGroup_DaoEx() throws Exception {
148         PdpGroup group = loadGroup("deleteGroup.json");
149
150         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
151
152         PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
153         doThrow(ex).when(session).deleteGroupFromDb(group);
154
155         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
156     }
157
158     /**
159      * Tests using a real provider, just to verify end-to-end functionality.
160      *
161      * @throws Exception if an error occurs
162      */
163     @Test
164     public void testUndeploy_Full() throws Exception {
165         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
166
167         PdpGroup group = loadGroup("undeploy.json");
168
169         when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group));
170         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
171
172         PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider();
173         deleteProvider.initialize();
174         deleteProvider.undeploy(fullIdent, DEFAULT_USER);
175
176         // should have updated the old group
177         List<PdpGroup> updates = getGroupUpdates();
178         assertEquals(1, updates.size());
179         assertSame(group, updates.get(0));
180         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
181
182         // should be one less item in the new subgroup
183         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
184
185         // should have updated the PDPs
186         List<PdpUpdate> requests = getUpdateRequests(1);
187         assertEquals(1, requests.size());
188         PdpUpdate req = requests.get(0);
189         assertEquals("pdpA", req.getName());
190         assertEquals(GROUP1_NAME, req.getPdpGroup());
191         assertEquals("pdpTypeA", req.getPdpSubgroup());
192         assertEquals(Arrays.asList(policy1.getIdentifier()), req.getPoliciesToBeUndeployed());
193     }
194
195     @Test
196     public void testUndeployPolicy_NotFound() throws Exception {
197         when(session.isUnchanged()).thenReturn(true);
198
199         assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class)
200                 .hasMessage("policy does not appear in any PDP group: policyA null");
201     }
202
203     @Test
204     public void testUndeployPolicy_DaoEx() throws Exception {
205         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
206
207         prov = spy(prov);
208         doThrow(exc).when(prov).processPolicy(any(), any());
209
210         assertThatThrownBy(() -> prov.undeploy(optIdent, null)).isSameAs(exc);
211     }
212
213     @Test
214     public void testUndeployPolicy_RtEx() throws Exception {
215         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
216
217         prov = spy(prov);
218         doThrow(exc).when(prov).processPolicy(any(), any());
219
220         // process method catches RuntimeException and re-throws as PfModelException
221         assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class)
222                 .hasRootCauseMessage(EXPECTED_EXCEPTION);
223     }
224
225     @Test
226     public void testMakeUpdater_WithVersion() throws PfModelException {
227         /*
228          * this group has two matching policies and one policy with a different name.
229          */
230         PdpGroup group = loadGroup("undeploy.json");
231
232         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
233         int origSize = subgroup.getPolicies().size();
234
235         // invoke updater - matching both name and version
236         assertTrue(updater.apply(group, subgroup));
237
238         // identified policy should have been removed
239         assertEquals(origSize - 1, subgroup.getPolicies().size());
240         assertFalse(subgroup.getPolicies().contains(ident));
241
242         verify(session).trackUndeploy(eq(ident), pdpCaptor.capture(), eq(group.getName()), eq(subgroup.getPdpType()));
243         assertEquals("[pdpA]", pdpCaptor.getValue().toString());
244     }
245
246     @Test
247     public void testMakeUpdater_NullVersion() throws PfModelException {
248         /*
249          * this group has two matching policies and one policy with a different name.
250          */
251         PdpGroup group = loadGroup("undeploy.json");
252
253         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
254         int origSize = subgroup.getPolicies().size();
255
256         // invoke updater - matching the name, but with a null (i.e., wild-card) version
257         updater = prov.makeUpdater(session, policy1, optIdent);
258         assertTrue(updater.apply(group, subgroup));
259
260         // identified policy should have been removed
261         assertEquals(origSize - 2, subgroup.getPolicies().size());
262         assertFalse(subgroup.getPolicies().contains(ident));
263     }
264
265     @Test
266     public void testMakeUpdater_NotFound() throws PfModelException {
267         /*
268          * this group has one policy with a different name and one with a different
269          * version, but not the policy of interest.
270          */
271         PdpGroup group = loadGroup("undeployMakeUpdaterGroupNotFound.json");
272
273         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
274         int origSize = subgroup.getPolicies().size();
275
276         // invoke updater
277         assertFalse(updater.apply(group, subgroup));
278
279         // should be unchanged
280         assertEquals(origSize, subgroup.getPolicies().size());
281     }
282
283     private class MyProvider extends PdpGroupDeleteProvider {
284         private MyProvider() {
285             super.initialize();
286         }
287
288         @Override
289         protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
290             processor.accept(session, request);
291         }
292
293         @Override
294         protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
295                 throws PfModelException {
296             // do nothing
297         }
298     }
299 }