Merge "Send pdp-update if PDP response doesn't match DB"
[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  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertSame;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.eq;
31 import static org.mockito.Mockito.doThrow;
32 import static org.mockito.Mockito.never;
33 import static org.mockito.Mockito.spy;
34 import static org.mockito.Mockito.verify;
35 import static org.mockito.Mockito.when;
36
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.Set;
40 import javax.ws.rs.core.Response.Status;
41 import org.assertj.core.api.Assertions;
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
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
89         super.setUp();
90
91         ident = policy1.getIdentifier();
92         optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null);
93         fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion());
94
95         prov = new MyProvider();
96
97         updater = prov.makeUpdater(session, policy1, fullIdent);
98     }
99
100     @Test
101     public void testDeleteGroup_Inctive() throws Exception {
102         PdpGroup group = loadGroup("deleteGroup.json");
103
104         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
105
106         prov.deleteGroup(GROUP1_NAME);
107
108         verify(session).deleteGroupFromDb(group);
109
110         // should be no PDP requests
111         verify(session, never()).addRequests(any(), any());
112     }
113
114     @Test
115     public void testDeleteGroup_Active() throws Exception {
116         PdpGroup group = loadGroup("deleteGroup.json");
117
118         group.setPdpGroupState(PdpState.ACTIVE);
119
120         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
121
122         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
123                         .hasMessage("group is still ACTIVE");
124     }
125
126     @Test
127     public void testDeleteGroup_NotFound() throws Exception {
128         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
129                         .hasMessage("group not found")
130                         .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
131                         .isEqualTo(Status.NOT_FOUND);
132     }
133
134     @Test
135     public void testDeleteGroup_Inactive() throws Exception {
136         PdpGroup group = loadGroup("deleteGroup.json");
137
138         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
139
140         prov.deleteGroup(GROUP1_NAME);
141
142         verify(session).deleteGroupFromDb(group);
143
144         // should done no requests for the PDPs
145         verify(session, never()).addRequests(any(), any());
146     }
147
148     @Test
149     public void testDeleteGroup_DaoEx() throws Exception {
150         PdpGroup group = loadGroup("deleteGroup.json");
151
152         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
153
154         PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
155         doThrow(ex).when(session).deleteGroupFromDb(group);
156
157         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
158     }
159
160     @Test
161     public void testUndeploy_testUndeployPolicy() {
162         Assertions.assertThatCode(() -> prov.undeploy(optIdent)).doesNotThrowAnyException();
163     }
164
165     /**
166      * Tests using a real provider, just to verify end-to-end functionality.
167      *
168      * @throws Exception if an error occurs
169      */
170     @Test
171     public void testUndeploy_Full() throws Exception {
172         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
173
174         PdpGroup group = loadGroup("undeploy.json");
175
176         when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group));
177         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
178
179         new PdpGroupDeleteProvider().undeploy(fullIdent);
180
181         // should have updated the old group
182         List<PdpGroup> updates = getGroupUpdates();
183         assertEquals(1, updates.size());
184         assertSame(group, updates.get(0));
185         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
186
187         // should be one less item in the new subgroup
188         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
189
190         // should have updated the PDPs
191         List<PdpUpdate> requests = getUpdateRequests(1);
192         assertEquals(1, requests.size());
193         PdpUpdate req = requests.get(0);
194         assertEquals("pdpA", req.getName());
195         assertEquals(GROUP1_NAME, req.getPdpGroup());
196         assertEquals("pdpTypeA", req.getPdpSubgroup());
197         assertEquals(Arrays.asList(policy1.getIdentifier()), req.getPoliciesToBeUndeployed());
198     }
199
200     @Test
201     public void testUndeployPolicy_NotFound() throws Exception {
202         when(session.isUnchanged()).thenReturn(true);
203
204         assertThatThrownBy(() -> prov.undeploy(optIdent)).isInstanceOf(PfModelException.class)
205                         .hasMessage("policy does not appear in any PDP group: policyA null");
206     }
207
208     @Test
209     public void testUndeployPolicy_DaoEx() throws Exception {
210         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
211
212         prov = spy(prov);
213         doThrow(exc).when(prov).processPolicy(any(), any());
214
215         assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
216     }
217
218     @Test
219     public void testUndeployPolicy_RtEx() throws Exception {
220         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
221
222         prov = spy(prov);
223         doThrow(exc).when(prov).processPolicy(any(), any());
224
225         assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
226     }
227
228     @Test
229     public void testMakeUpdater_WithVersion() throws PfModelException {
230         /*
231          * this group has two matching policies and one policy with a different name.
232          */
233         PdpGroup group = loadGroup("undeploy.json");
234
235         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
236         int origSize = subgroup.getPolicies().size();
237
238         // invoke updater - matching both name and version
239         assertTrue(updater.apply(group, subgroup));
240
241         // identified policy should have been removed
242         assertEquals(origSize - 1, subgroup.getPolicies().size());
243         assertFalse(subgroup.getPolicies().contains(ident));
244
245         verify(session).trackUndeploy(eq(ident), pdpCaptor.capture(), eq(group.getName()), eq(subgroup.getPdpType()));
246         assertEquals("[pdpA]", pdpCaptor.getValue().toString());
247     }
248
249     @Test
250     public void testMakeUpdater_NullVersion() throws PfModelException {
251         /*
252          * this group has two matching policies and one policy with a different name.
253          */
254         PdpGroup group = loadGroup("undeploy.json");
255
256         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
257         int origSize = subgroup.getPolicies().size();
258
259         // invoke updater - matching the name, but with a null (i.e., wild-card) version
260         updater = prov.makeUpdater(session, policy1, optIdent);
261         assertTrue(updater.apply(group, subgroup));
262
263         // identified policy should have been removed
264         assertEquals(origSize - 2, subgroup.getPolicies().size());
265         assertFalse(subgroup.getPolicies().contains(ident));
266     }
267
268     @Test
269     public void testMakeUpdater_NotFound() throws PfModelException {
270         /*
271          * this group has one policy with a different name and one with a different
272          * version, but not the policy of interest.
273          */
274         PdpGroup group = loadGroup("undeployMakeUpdaterGroupNotFound.json");
275
276         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
277         int origSize = subgroup.getPolicies().size();
278
279         // invoke updater
280         assertFalse(updater.apply(group, subgroup));
281
282         // should be unchanged
283         assertEquals(origSize, subgroup.getPolicies().size());
284     }
285
286
287     private class MyProvider extends PdpGroupDeleteProvider {
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 }