PolicyAudit creation when deploy/undeploy triggered.
[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.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.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.pdp.concepts.PdpGroup;
50 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
51 import org.onap.policy.models.pdp.concepts.PdpUpdate;
52 import org.onap.policy.models.pdp.enums.PdpState;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
55 import org.onap.policy.pap.main.rest.ProviderBase.Updater;
56
57 public class TestPdpGroupDeleteProvider extends ProviderSuper {
58     private static final String EXPECTED_EXCEPTION = "expected exception";
59     private static final String GROUP1_NAME = "groupA";
60
61     @Mock
62     private SessionData session;
63
64     @Captor
65     private ArgumentCaptor<Set<String>> pdpCaptor;
66
67     private MyProvider prov;
68     private ToscaConceptIdentifierOptVersion optIdent;
69     private ToscaConceptIdentifierOptVersion fullIdent;
70     private ToscaConceptIdentifier ident;
71     private Updater updater;
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     @Override
85     public void setUp() throws Exception {
86
87         super.setUp();
88
89         ident = policy1.getIdentifier();
90         optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null);
91         fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion());
92
93         prov = new MyProvider();
94
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         new PdpGroupDeleteProvider().undeploy(fullIdent, DEFAULT_USER);
173
174         // should have updated the old group
175         List<PdpGroup> updates = getGroupUpdates();
176         assertEquals(1, updates.size());
177         assertSame(group, updates.get(0));
178         assertEquals(PdpState.ACTIVE, group.getPdpGroupState());
179
180         // should be one less item in the new subgroup
181         assertEquals(2, group.getPdpSubgroups().get(0).getPolicies().size());
182
183         // should have updated the PDPs
184         List<PdpUpdate> requests = getUpdateRequests(1);
185         assertEquals(1, requests.size());
186         PdpUpdate req = requests.get(0);
187         assertEquals("pdpA", req.getName());
188         assertEquals(GROUP1_NAME, req.getPdpGroup());
189         assertEquals("pdpTypeA", req.getPdpSubgroup());
190         assertEquals(Arrays.asList(policy1.getIdentifier()), req.getPoliciesToBeUndeployed());
191     }
192
193     @Test
194     public void testUndeployPolicy_NotFound() throws Exception {
195         when(session.isUnchanged()).thenReturn(true);
196
197         assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class)
198                 .hasMessage("policy does not appear in any PDP group: policyA null");
199     }
200
201     @Test
202     public void testUndeployPolicy_DaoEx() throws Exception {
203         PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
204
205         prov = spy(prov);
206         doThrow(exc).when(prov).processPolicy(any(), any());
207
208         assertThatThrownBy(() -> prov.undeploy(optIdent, null)).isSameAs(exc);
209     }
210
211     @Test
212     public void testUndeployPolicy_RtEx() throws Exception {
213         RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
214
215         prov = spy(prov);
216         doThrow(exc).when(prov).processPolicy(any(), any());
217
218         // process method catches RuntimeException and re-throws as PfModelException
219         assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class)
220                 .hasRootCauseMessage(EXPECTED_EXCEPTION);
221     }
222
223     @Test
224     public void testMakeUpdater_WithVersion() throws PfModelException {
225         /*
226          * this group has two matching policies and one policy with a different name.
227          */
228         PdpGroup group = loadGroup("undeploy.json");
229
230         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
231         int origSize = subgroup.getPolicies().size();
232
233         // invoke updater - matching both name and version
234         assertTrue(updater.apply(group, subgroup));
235
236         // identified policy should have been removed
237         assertEquals(origSize - 1, subgroup.getPolicies().size());
238         assertFalse(subgroup.getPolicies().contains(ident));
239
240         verify(session).trackUndeploy(eq(ident), pdpCaptor.capture(), eq(group.getName()), eq(subgroup.getPdpType()));
241         assertEquals("[pdpA]", pdpCaptor.getValue().toString());
242     }
243
244     @Test
245     public void testMakeUpdater_NullVersion() throws PfModelException {
246         /*
247          * this group has two matching policies and one policy with a different name.
248          */
249         PdpGroup group = loadGroup("undeploy.json");
250
251         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
252         int origSize = subgroup.getPolicies().size();
253
254         // invoke updater - matching the name, but with a null (i.e., wild-card) version
255         updater = prov.makeUpdater(session, policy1, optIdent);
256         assertTrue(updater.apply(group, subgroup));
257
258         // identified policy should have been removed
259         assertEquals(origSize - 2, subgroup.getPolicies().size());
260         assertFalse(subgroup.getPolicies().contains(ident));
261     }
262
263     @Test
264     public void testMakeUpdater_NotFound() throws PfModelException {
265         /*
266          * this group has one policy with a different name and one with a different
267          * version, but not the policy of interest.
268          */
269         PdpGroup group = loadGroup("undeployMakeUpdaterGroupNotFound.json");
270
271         PdpSubGroup subgroup = group.getPdpSubgroups().get(0);
272         int origSize = subgroup.getPolicies().size();
273
274         // invoke updater
275         assertFalse(updater.apply(group, subgroup));
276
277         // should be unchanged
278         assertEquals(origSize, subgroup.getPolicies().size());
279     }
280
281     private class MyProvider extends PdpGroupDeleteProvider {
282
283         @Override
284         protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
285             processor.accept(session, request);
286         }
287
288         @Override
289         protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
290                 throws PfModelException {
291             // do nothing
292         }
293     }
294 }