Generate notifications when policies change
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / depundep / TestPdpGroupDeleteProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.main.rest.depundep;
22
23 import static org.assertj.core.api.Assertions.assertThatThrownBy;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertSame;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Matchers.any;
29 import static org.mockito.Matchers.eq;
30 import static org.mockito.Mockito.doThrow;
31 import static org.mockito.Mockito.never;
32 import static org.mockito.Mockito.spy;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
35
36 import java.util.Arrays;
37 import java.util.List;
38 import java.util.Set;
39 import javax.ws.rs.core.Response.Status;
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.Test;
43 import org.mockito.ArgumentCaptor;
44 import org.mockito.Captor;
45 import org.mockito.Mock;
46 import org.onap.policy.common.utils.services.Registry;
47 import org.onap.policy.models.base.PfModelException;
48 import org.onap.policy.models.pdp.concepts.PdpGroup;
49 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
50 import org.onap.policy.models.pdp.concepts.PdpUpdate;
51 import org.onap.policy.models.pdp.enums.PdpState;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifierOptVersion;
54 import org.onap.policy.pap.main.rest.depundep.ProviderBase.Updater;
55
56 public class TestPdpGroupDeleteProvider extends ProviderSuper {
57     private static final String EXPECTED_EXCEPTION = "expected exception";
58     private static final String GROUP1_NAME = "groupA";
59
60     @Mock
61     private SessionData session;
62
63     @Captor
64     private ArgumentCaptor<Set<String>> pdpCaptor;
65
66     private MyProvider prov;
67     private ToscaPolicyIdentifierOptVersion optIdent;
68     private ToscaPolicyIdentifierOptVersion fullIdent;
69     private ToscaPolicyIdentifier ident;
70     private Updater updater;
71
72
73     @AfterClass
74     public static void tearDownAfterClass() {
75         Registry.newRegistry();
76     }
77
78     /**
79      * Configures mocks and objects.
80      *
81      * @throws Exception if an error occurs
82      */
83     @Before
84     public void setUp() throws Exception {
85
86         super.setUp();
87
88         ident = policy1.getIdentifier();
89         optIdent = new ToscaPolicyIdentifierOptVersion(ident.getName(), null);
90         fullIdent = new ToscaPolicyIdentifierOptVersion(ident.getName(), ident.getVersion());
91
92         prov = new MyProvider();
93
94         updater = prov.makeUpdater(session, policy1, fullIdent);
95     }
96
97     @Test
98     public void testDeleteGroup_Inctive() throws Exception {
99         PdpGroup group = loadGroup("deleteGroup.json");
100
101         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
102
103         prov.deleteGroup(GROUP1_NAME);
104
105         verify(session).deleteGroupFromDb(group);
106
107         // should be no PDP requests
108         verify(session, never()).addRequests(any(), any());
109     }
110
111     @Test
112     public void testDeleteGroup_Active() throws Exception {
113         PdpGroup group = loadGroup("deleteGroup.json");
114
115         group.setPdpGroupState(PdpState.ACTIVE);
116
117         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
118
119         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
120                         .hasMessage("group is still ACTIVE");
121     }
122
123     @Test
124     public void testDeleteGroup_NotFound() throws Exception {
125         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
126                         .hasMessage("group not found")
127                         .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
128                         .isEqualTo(Status.NOT_FOUND);
129     }
130
131     @Test
132     public void testDeleteGroup_Inactive() throws Exception {
133         PdpGroup group = loadGroup("deleteGroup.json");
134
135         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
136
137         prov.deleteGroup(GROUP1_NAME);
138
139         verify(session).deleteGroupFromDb(group);
140
141         // should done no requests for the PDPs
142         verify(session, never()).addRequests(any(), any());
143     }
144
145     @Test
146     public void testDeleteGroup_DaoEx() throws Exception {
147         PdpGroup group = loadGroup("deleteGroup.json");
148
149         when(session.getGroup(GROUP1_NAME)).thenReturn(group);
150
151         PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
152         doThrow(ex).when(session).deleteGroupFromDb(group);
153
154         assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
155     }
156
157     @Test
158     public void testUndeploy_testUndeployPolicy() throws Exception {
159         prov.undeploy(optIdent);
160     }
161
162     /**
163      * Tests using a real provider, just to verify end-to-end functionality.
164      *
165      * @throws Exception if an error occurs
166      */
167     @Test
168     public void testUndeploy_Full() throws Exception {
169         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
170
171         PdpGroup group = loadGroup("undeploy.json");
172
173         when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group));
174         when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
175
176         new PdpGroupDeleteProvider().undeploy(fullIdent);
177
178         // should have updated the old group
179         List<PdpGroup> updates = getGroupUpdates();
180         assertEquals(1, updates.size());
181         assertSame(group, updates.get(0));
182         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
183
184         // should be one less item in the new subgroup
185         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
186
187         // should have updated the PDPs
188         List<PdpUpdate> requests = getUpdateRequests(1);
189         assertEquals(1, requests.size());
190         PdpUpdate req = requests.get(0);
191         assertEquals("pdpA", req.getName());
192         assertEquals(GROUP1_NAME, req.getPdpGroup());
193         assertEquals("pdpTypeA", req.getPdpSubgroup());
194         assertEquals(Arrays.asList(policy1, policy1), req.getPolicies());
195     }
196
197     @Test
198     public void testUndeployPolicy_NotFound() throws Exception {
199         when(session.isUnchanged()).thenReturn(true);
200
201         assertThatThrownBy(() -> prov.undeploy(optIdent)).isInstanceOf(PfModelException.class)
202                         .hasMessage("policy does not appear in any PDP group: policyA null");
203     }
204
205     @Test
206     public void testUndeployPolicy_DaoEx() throws Exception {
207         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
208
209         prov = spy(prov);
210         doThrow(exc).when(prov).processPolicy(any(), any());
211
212         assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
213     }
214
215     @Test
216     public void testUndeployPolicy_RtEx() throws Exception {
217         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
218
219         prov = spy(prov);
220         doThrow(exc).when(prov).processPolicy(any(), any());
221
222         assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
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());
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
284     private class MyProvider extends PdpGroupDeleteProvider {
285
286         @Override
287         protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
288             processor.accept(session, request);
289         }
290
291         @Override
292         protected void processPolicy(SessionData data, ToscaPolicyIdentifierOptVersion desiredPolicy)
293                         throws PfModelException {
294             // do nothing
295         }
296     }
297 }