2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.pap.main.rest;
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;
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;
54 public class TestProviderBase extends ProviderSuper {
55 private static final String EXPECTED_EXCEPTION = "expected exception";
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";
70 private MyProvider prov;
74 public static void tearDownAfterClass() {
75 Registry.newRegistry();
79 * Configures mocks and objects.
81 * @throws Exception if an error occurs
85 public void setUp() throws Exception {
89 when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"));
91 prov = new MyProvider();
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"));
102 public void testProcess() throws Exception {
103 prov.process(loadRequest(), this::handle);
105 assertGroup(getGroupUpdates(), GROUP1_NAME);
107 assertUpdate(getUpdateRequests(1), GROUP1_NAME, PDP1_TYPE, PDP1);
109 checkEmptyNotification();
113 public void testProcess_CreateEx() throws Exception {
114 PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
115 when(daofact.create()).thenThrow(ex);
117 assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex);
121 public void testProcess_PfRtEx() throws Exception {
122 PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
123 when(daofact.create()).thenThrow(ex);
125 assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex);
129 public void testProcess_RuntimeEx() throws Exception {
130 RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION);
131 when(daofact.create()).thenThrow(ex);
133 assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isInstanceOf(PfModelException.class)
134 .hasMessage("request failed").hasCause(ex);
138 public void testProcessPolicy_NoGroups() throws Exception {
139 when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList());
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");
149 public void testGetPolicy() throws Exception {
150 PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION);
151 when(dao.getFilteredPolicyList(any())).thenThrow(exc);
153 ToscaConceptIdentifierOptVersion req = loadRequest();
154 assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class)
159 public void testGetPolicy_NotFound() throws Exception {
160 when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
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);
170 public void testGetGroup() throws Exception {
171 when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json"))
172 .thenReturn(loadGroups("groups.json"));
174 prov.process(loadRequest(), this::handle);
176 assertGroup(getGroupUpdates(), GROUP1_NAME);
180 public void testUpgradeGroup() throws Exception {
182 * Each subgroup has a different PDP type and name.
184 * Type is not supported by the first subgroup.
186 * Second subgroup matches.
188 * Third subgroup already contains the policy.
190 * Last subgroup matches.
193 when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json"));
196 prov.add(false, true, false, true);
198 prov.process(loadRequest(), this::handle);
200 assertGroup(getGroupUpdates(), GROUP1_NAME);
202 List<PdpUpdate> requests = getUpdateRequests(2);
203 assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2);
204 assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4);
208 public void testUpgradeGroup_Multiple() throws Exception {
210 * Policy data in the DB: policy1=type1, policy2=type2, policy3=type3,
213 * Group data in the DB: group1=(type1=pdp1, type3=pdp3) group2=(type2=pdp2)
215 * Request specifies: policy1, policy2, policy3, policy4
217 * Should create new versions of group1 and group2.
219 * Should update old versions of group1 and group2. Should also update new version
222 * Should generate updates to pdp1, pdp2, and pdp3.
225 when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"))
226 .thenReturn(loadPolicies("upgradeGroupPolicy2.json"))
227 .thenReturn(loadPolicies("upgradeGroupPolicy3.json"))
228 .thenReturn(loadPolicies("upgradeGroupPolicy4.json"));
230 List<PdpGroup> groups1 = loadGroups("upgradeGroupGroup1.json");
231 List<PdpGroup> groups2 = loadGroups("upgradeGroupGroup2.json");
234 * these are in pairs of (get-group, get-max-group) matching each policy in the
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);
245 // multiple policies in the request
246 PdpDeployPolicies request = loadFile("updateGroupReqMultiple.json", PdpDeployPolicies.class);
248 prov.process(request, (data, deploy) -> {
249 for (ToscaConceptIdentifierOptVersion policy : deploy.getPolicies()) {
250 handle(data, policy);
255 List<PdpGroup> changes = getGroupUpdates();
256 assertGroup(changes, GROUP1_NAME);
257 assertGroup(changes, GROUP2_NAME);
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);
266 public void testUpgradeGroup_NothingUpdated() throws Exception {
270 prov.process(loadRequest(), this::handle);
272 verify(dao, never()).createPdpGroups(any());
273 verify(dao, never()).updatePdpGroups(any());
274 verify(reqmap, never()).addRequest(any(PdpUpdate.class));
278 protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
280 PdpUpdate update = updates.remove(0);
282 assertEquals(groupName, update.getPdpGroup());
283 assertEquals(pdpType, update.getPdpSubgroup());
284 assertEquals(pdpName, update.getName());
285 assertTrue(update.getPoliciesToBeDeployed().contains(policy1));
289 * Loads a standard request.
291 * @return a standard request
293 protected ToscaConceptIdentifierOptVersion loadRequest() {
294 return loadRequest("requestBase.json");
298 * Loads a request from a JSON file.
300 * @param fileName name of the file from which to load
301 * @return the request that was loaded
303 protected ToscaConceptIdentifierOptVersion loadRequest(String fileName) {
304 return loadFile(fileName, PapPolicyIdentifier.class).getGenericIdentifier();
308 * Loads an empty request.
310 * @return an empty request
312 protected ToscaConceptIdentifierOptVersion loadEmptyRequest() {
313 return loadRequest("emptyRequestBase.json");
317 * Handles a request by invoking the provider's processPolicy method.
319 * @param data session data
320 * @param request request to be handled
321 * @throws PfModelException if an error occurred
323 private void handle(SessionData data, ToscaConceptIdentifierOptVersion request) throws PfModelException {
324 prov.processPolicy(data, request);
328 private static class MyProvider extends ProviderBase {
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.
334 private final Queue<Boolean> shouldUpdate = new LinkedList<>();
337 * Constructs the object and queues up several successful updates.
339 public MyProvider() {
340 for (int x = 0; x < 10; ++x) {
341 shouldUpdate.add(true);
345 public void clear() {
346 shouldUpdate.clear();
349 public void add(Boolean... update) {
350 shouldUpdate.addAll(Arrays.asList(update));
354 protected Updater makeUpdater(SessionData data, ToscaPolicy policy,
355 ToscaConceptIdentifierOptVersion desiredPolicy) {
357 return (group, subgroup) -> {
358 if (shouldUpdate.remove()) {
359 ToscaConceptIdentifier ident1 = policy.getIdentifier();
361 // queue indicated that the update should succeed
362 subgroup.getPolicies().add(ident1);
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);
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);
375 // queue indicated that no update should be made this time