Merge "Send pdp-update if PDP response doesn't match DB"
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / TestProviderBase.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) 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.assertSame;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.ArgumentMatchers.any;
29 import static org.mockito.Mockito.never;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32
33 import java.util.Arrays;
34 import java.util.Collections;
35 import java.util.LinkedList;
36 import java.util.List;
37 import java.util.Queue;
38 import javax.ws.rs.core.Response.Status;
39 import org.junit.AfterClass;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.common.utils.services.Registry;
43 import org.onap.policy.models.base.PfModelException;
44 import org.onap.policy.models.base.PfModelRuntimeException;
45 import org.onap.policy.models.pap.concepts.PapPolicyIdentifier;
46 import org.onap.policy.models.pap.concepts.PdpDeployPolicies;
47 import org.onap.policy.models.pdp.concepts.PdpGroup;
48 import org.onap.policy.models.pdp.concepts.PdpUpdate;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
52 import org.powermock.reflect.Whitebox;
53
54 public class TestProviderBase extends ProviderSuper {
55     private static final String EXPECTED_EXCEPTION = "expected exception";
56
57     private static final String POLICY1_NAME = "policyA";
58     private static final String POLICY1_VERSION = "1.2.3";
59     private static final String GROUP1_NAME = "groupA";
60     private static final String GROUP2_NAME = "groupB";
61     private static final String PDP1_TYPE = "pdpTypeA";
62     private static final String PDP2_TYPE = "pdpTypeB";
63     private static final String PDP3_TYPE = "pdpTypeC";
64     private static final String PDP4_TYPE = "pdpTypeD";
65     private static final String PDP1 = "pdpA";
66     private static final String PDP2 = "pdpB";
67     private static final String PDP3 = "pdpC";
68     private static final String PDP4 = "pdpD";
69
70     private MyProvider prov;
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     @Override
84     @Before
85     public void setUp() throws Exception {
86
87         super.setUp();
88
89         when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"));
90
91         prov = new MyProvider();
92     }
93
94     @Test
95     public void testProviderBase() {
96         assertSame(lockit, Whitebox.getInternalState(prov, "updateLock"));
97         assertSame(reqmap, Whitebox.getInternalState(prov, "requestMap"));
98         assertSame(daofact, Whitebox.getInternalState(prov, "daoFactory"));
99     }
100
101     @Test
102     public void testProcess() throws Exception {
103         prov.process(loadRequest(), this::handle);
104
105         assertGroup(getGroupUpdates(), GROUP1_NAME);
106
107         assertUpdate(getUpdateRequests(1), GROUP1_NAME, PDP1_TYPE, PDP1);
108
109         checkEmptyNotification();
110     }
111
112     @Test
113     public void testProcess_CreateEx() throws Exception {
114         PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
115         when(daofact.create()).thenThrow(ex);
116
117         assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex);
118     }
119
120     @Test
121     public void testProcess_PfRtEx() throws Exception {
122         PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
123         when(daofact.create()).thenThrow(ex);
124
125         assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex);
126     }
127
128     @Test
129     public void testProcess_RuntimeEx() throws Exception {
130         RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION);
131         when(daofact.create()).thenThrow(ex);
132
133         assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isInstanceOf(PfModelException.class)
134                         .hasMessage("request failed").hasCause(ex);
135     }
136
137     @Test
138     public void testProcessPolicy_NoGroups() throws Exception {
139         when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList());
140
141         SessionData session = new SessionData(dao);
142         ToscaConceptIdentifierOptVersion ident = new ToscaConceptIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION);
143         assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PfModelException.class)
144                         .hasMessage("policy not supported by any PDP group: policyA 1.2.3");
145
146     }
147
148     @Test
149     public void testGetPolicy() throws Exception {
150         PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION);
151         when(dao.getFilteredPolicyList(any())).thenThrow(exc);
152
153         ToscaConceptIdentifierOptVersion req = loadRequest();
154         assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class)
155                         .hasCause(exc);
156     }
157
158     @Test
159     public void testGetPolicy_NotFound() throws Exception {
160         when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
161
162         ToscaConceptIdentifierOptVersion req = loadRequest();
163         assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class)
164                         .hasMessage("cannot find policy: policyA 1.2.3")
165                         .extracting(ex -> ((PfModelRuntimeException) ex).getErrorResponse().getResponseCode())
166                         .isEqualTo(Status.NOT_FOUND);
167     }
168
169     @Test
170     public void testGetGroup() throws Exception {
171         when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json"))
172                         .thenReturn(loadGroups("groups.json"));
173
174         prov.process(loadRequest(), this::handle);
175
176         assertGroup(getGroupUpdates(), GROUP1_NAME);
177     }
178
179     @Test
180     public void testUpgradeGroup() throws Exception {
181         /*
182          * Each subgroup has a different PDP type and name.
183          *
184          * Type is not supported by the first subgroup.
185          *
186          * Second subgroup matches.
187          *
188          * Third subgroup already contains the policy.
189          *
190          * Last subgroup matches.
191          */
192
193         when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json"));
194
195         prov.clear();
196         prov.add(false, true, false, true);
197
198         prov.process(loadRequest(), this::handle);
199
200         assertGroup(getGroupUpdates(), GROUP1_NAME);
201
202         List<PdpUpdate> requests = getUpdateRequests(2);
203         assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2);
204         assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4);
205     }
206
207     @Test
208     public void testUpgradeGroup_Multiple() throws Exception {
209         /*
210          * Policy data in the DB: policy1=type1, policy2=type2, policy3=type3,
211          * policy4=type1
212          *
213          * Group data in the DB: group1=(type1=pdp1, type3=pdp3) group2=(type2=pdp2)
214          *
215          * Request specifies: policy1, policy2, policy3, policy4
216          *
217          * Should create new versions of group1 and group2.
218          *
219          * Should update old versions of group1 and group2. Should also update new version
220          * of group1 twice.
221          *
222          * Should generate updates to pdp1, pdp2, and pdp3.
223          */
224
225         when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"))
226                         .thenReturn(loadPolicies("upgradeGroupPolicy2.json"))
227                         .thenReturn(loadPolicies("upgradeGroupPolicy3.json"))
228                         .thenReturn(loadPolicies("upgradeGroupPolicy4.json"));
229
230         List<PdpGroup> groups1 = loadGroups("upgradeGroupGroup1.json");
231         List<PdpGroup> groups2 = loadGroups("upgradeGroupGroup2.json");
232
233         /*
234          * these are in pairs of (get-group, get-max-group) matching each policy in the
235          * request
236          */
237         // @formatter:off
238         when(dao.getFilteredPdpGroups(any()))
239             .thenReturn(groups1).thenReturn(groups1)
240             .thenReturn(groups2).thenReturn(groups2)
241             .thenReturn(groups1).thenReturn(groups1)
242             .thenReturn(groups1).thenReturn(groups1);
243         // @formatter:on
244
245         // multiple policies in the request
246         PdpDeployPolicies request = loadFile("updateGroupReqMultiple.json", PdpDeployPolicies.class);
247
248         prov.process(request, (data, deploy) -> {
249             for (ToscaConceptIdentifierOptVersion policy : deploy.getPolicies()) {
250                 handle(data, policy);
251             }
252         });
253
254         // verify updates
255         List<PdpGroup> changes = getGroupUpdates();
256         assertGroup(changes, GROUP1_NAME);
257         assertGroup(changes, GROUP2_NAME);
258
259         List<PdpUpdate> requests = getUpdateRequests(3);
260         assertUpdateIgnorePolicy(requests, GROUP1_NAME, PDP1_TYPE, PDP1);
261         assertUpdateIgnorePolicy(requests, GROUP2_NAME, PDP2_TYPE, PDP2);
262         assertUpdateIgnorePolicy(requests, GROUP1_NAME, PDP3_TYPE, PDP3);
263     }
264
265     @Test
266     public void testUpgradeGroup_NothingUpdated() throws Exception {
267         prov.clear();
268         prov.add(false);
269
270         prov.process(loadRequest(), this::handle);
271
272         verify(dao, never()).createPdpGroups(any());
273         verify(dao, never()).updatePdpGroups(any());
274         verify(reqmap, never()).addRequest(any(PdpUpdate.class));
275     }
276
277
278     protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
279
280         PdpUpdate update = updates.remove(0);
281
282         assertEquals(groupName, update.getPdpGroup());
283         assertEquals(pdpType, update.getPdpSubgroup());
284         assertEquals(pdpName, update.getName());
285         assertTrue(update.getPoliciesToBeDeployed().contains(policy1));
286     }
287
288     /**
289      * Loads a standard request.
290      *
291      * @return a standard request
292      */
293     protected ToscaConceptIdentifierOptVersion loadRequest() {
294         return loadRequest("requestBase.json");
295     }
296
297     /**
298      * Loads a request from a JSON file.
299      *
300      * @param fileName name of the file from which to load
301      * @return the request that was loaded
302      */
303     protected ToscaConceptIdentifierOptVersion loadRequest(String fileName) {
304         return loadFile(fileName, PapPolicyIdentifier.class).getGenericIdentifier();
305     }
306
307     /**
308      * Loads an empty request.
309      *
310      * @return an empty request
311      */
312     protected ToscaConceptIdentifierOptVersion loadEmptyRequest() {
313         return loadRequest("emptyRequestBase.json");
314     }
315
316     /**
317      * Handles a request by invoking the provider's processPolicy method.
318      *
319      * @param data session data
320      * @param request request to be handled
321      * @throws PfModelException if an error occurred
322      */
323     private void handle(SessionData data, ToscaConceptIdentifierOptVersion request) throws PfModelException {
324         prov.processPolicy(data, request);
325     }
326
327
328     private static class MyProvider extends ProviderBase {
329         /**
330          * Used to determine whether or not to make an update when
331          * {@link #makeUpdater(ToscaPolicy)} is called. The updater function removes an
332          * item from this queue each time it is invoked.
333          */
334         private final Queue<Boolean> shouldUpdate = new LinkedList<>();
335
336         /**
337          * Constructs the object and queues up several successful updates.
338          */
339         public MyProvider() {
340             for (int x = 0; x < 10; ++x) {
341                 shouldUpdate.add(true);
342             }
343         }
344
345         public void clear() {
346             shouldUpdate.clear();
347         }
348
349         public void add(Boolean... update) {
350             shouldUpdate.addAll(Arrays.asList(update));
351         }
352
353         @Override
354         protected Updater makeUpdater(SessionData data, ToscaPolicy policy,
355                         ToscaConceptIdentifierOptVersion desiredPolicy) {
356
357             return (group, subgroup) -> {
358                 if (shouldUpdate.remove()) {
359                     ToscaConceptIdentifier ident1 = policy.getIdentifier();
360
361                     // queue indicated that the update should succeed
362                     subgroup.getPolicies().add(ident1);
363
364                     ToscaPolicy testPolicy1 = data.getPolicy(new ToscaConceptIdentifierOptVersion(ident1));
365                     data.trackDeploy(testPolicy1, Collections.singleton(PDP1), GROUP1_NAME, PDP1_TYPE);
366                     data.trackUndeploy(ident1, Collections.singleton(PDP2), GROUP1_NAME, PDP2_TYPE);
367
368                     ToscaConceptIdentifier ident2 = new ToscaConceptIdentifier(POLICY1_NAME, "9.9.9");
369                     ToscaPolicy testPolicy2 = data.getPolicy(new ToscaConceptIdentifierOptVersion(ident2));
370                     data.trackDeploy(testPolicy2, Collections.singleton(PDP3), GROUP1_NAME, PDP3_TYPE);
371                     data.trackUndeploy(ident2, Collections.singleton(PDP4), GROUP1_NAME, PDP4_TYPE);
372                     return true;
373
374                 } else {
375                     // queue indicated that no update should be made this time
376                     return false;
377                 }
378             };
379         }
380     }
381 }