31e22e3fe91afce4e0597d7230765171d860c9e8
[policy/api.git] / main / src / test / java / org / onap / policy / api / main / rest / provider / TestLegacyOperationalPolicyProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 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  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.rest.provider;
25
26 import static org.assertj.core.api.Assertions.assertThatCode;
27 import static org.assertj.core.api.Assertions.assertThatThrownBy;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertFalse;
30 import static org.junit.Assert.assertNotNull;
31 import static org.junit.Assert.assertTrue;
32 import static org.junit.Assert.fail;
33
34 import java.util.ArrayList;
35 import java.util.Base64;
36 import java.util.Collections;
37 import java.util.List;
38
39 import org.junit.After;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.api.main.parameters.ApiParameterGroup;
43 import org.onap.policy.common.parameters.ParameterService;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.common.utils.coder.StandardYamlCoder;
46 import org.onap.policy.common.utils.resources.ResourceUtils;
47 import org.onap.policy.models.base.PfModelException;
48 import org.onap.policy.models.pdp.concepts.Pdp;
49 import org.onap.policy.models.pdp.concepts.PdpGroup;
50 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
51 import org.onap.policy.models.pdp.concepts.PdpSubGroup;
52 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
53 import org.onap.policy.models.pdp.enums.PdpState;
54 import org.onap.policy.models.provider.PolicyModelsProvider;
55 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
56 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
60 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
61
62 /**
63  * This class performs unit test of {@link LegacyOperationalPolicyProvider}.
64  *
65  * @author Chenfei Gao (cgao@research.att.com)
66  */
67 public class TestLegacyOperationalPolicyProvider {
68
69     private static LegacyOperationalPolicyProvider operationalPolicyProvider;
70     private static PolicyTypeProvider policyTypeProvider;
71     private static PolicyModelsProviderParameters providerParams;
72     private static ApiParameterGroup apiParamGroup;
73     private static StandardCoder standardCoder;
74     private static StandardYamlCoder standardYamlCoder;
75
76     private static final String POLICY_RESOURCE = "policies/vCPE.policy.operational.input.json";
77     private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policies.controlloop.Operational.yaml";
78     private static final String POLICY_TYPE_ID = "onap.policies.controlloop.Operational:1.0.0";
79     private static final String POLICY_ID = "operational.restart:1.0.0";
80     private static final String POLICY_NAME = "operational.restart";
81     private static final String POLICY_VERSION = "1";
82     private static final String POLICY_TYPE_NAME = "onap.policies.controlloop.Operational";
83     private static final String POLICY_TYPE_VERSION = "1.0.0";
84     private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
85
86     /**
87      * Initializes parameters.
88      *
89      * @throws PfModelException the PfModel parsing exception
90      */
91     @Before
92     public void setupParameters() throws PfModelException {
93
94         standardCoder = new StandardCoder();
95         standardYamlCoder = new StandardYamlCoder();
96         providerParams = new PolicyModelsProviderParameters();
97         providerParams.setDatabaseDriver("org.h2.Driver");
98         providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
99         providerParams.setDatabaseUser("policy");
100         providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
101         providerParams.setPersistenceUnit("ToscaConceptTest");
102         apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList());
103         ParameterService.register(apiParamGroup, true);
104         operationalPolicyProvider = new LegacyOperationalPolicyProvider();
105         policyTypeProvider = new PolicyTypeProvider();
106     }
107
108     /**
109      * Closes up DB connections and deregisters API parameter group.
110      *
111      * @throws PfModelException the PfModel parsing exception
112      */
113     @After
114     public void tearDown() throws PfModelException {
115
116         operationalPolicyProvider.close();
117         policyTypeProvider.close();
118         ParameterService.deregister(apiParamGroup);
119     }
120
121     @Test
122     public void testFetchOperationalPolicy() {
123
124         assertThatThrownBy(() -> {
125             operationalPolicyProvider.fetchOperationalPolicy("dummy", null);
126         }).hasMessage("no policy found for policy: dummy:null");
127
128         assertThatThrownBy(() -> {
129             operationalPolicyProvider.fetchOperationalPolicy("dummy", "dummy");
130         }).hasMessage("legacy policy version is not an integer");
131
132         assertThatCode(() -> {
133             ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder.decode(
134                     ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
135             policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
136
137             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
138             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
139             LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
140             assertNotNull(createdPolicy);
141
142             policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
143             policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
144             createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
145             assertNotNull(createdPolicy);
146
147             LegacyOperationalPolicy firstVersion =
148                     operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1");
149             assertNotNull(firstVersion);
150             assertEquals("1", firstVersion.getPolicyVersion());
151
152             LegacyOperationalPolicy latestVersion =
153                     operationalPolicyProvider.fetchOperationalPolicy("operational.restart", null);
154             assertNotNull(latestVersion);
155             assertEquals("2", latestVersion.getPolicyVersion());
156         }).doesNotThrowAnyException();
157
158         assertThatThrownBy(() -> {
159             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "1.0.0");
160         }).hasMessage("legacy policy version is not an integer");
161
162         assertThatThrownBy(() -> {
163             operationalPolicyProvider.fetchOperationalPolicy("operational.restart", "latest");;
164         }).hasMessage("legacy policy version is not an integer");
165
166         assertThatCode(() -> {
167             operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
168             operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "2");
169             policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
170         }).doesNotThrowAnyException();
171     }
172
173     @Test
174     public void testFetchDeployedOperationalPolicies() {
175
176         assertThatThrownBy(() -> {
177             operationalPolicyProvider.fetchDeployedOperationalPolicies("dummy");
178         }).hasMessage("could not find policy with ID dummy and type " + POLICY_TYPE_ID + " deployed in any pdp group");
179
180         try (PolicyModelsProvider databaseProvider =
181                 new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
182             assertEquals(0, databaseProvider.getPdpGroups("name").size());
183             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
184
185             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
186             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
187
188             PdpGroup pdpGroup = new PdpGroup();
189             pdpGroup.setName("group");
190             pdpGroup.setVersion("1.2.3");
191             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
192             pdpGroup.setPdpSubgroups(new ArrayList<>());
193             List<PdpGroup> groupList = new ArrayList<>();
194             groupList.add(pdpGroup);
195
196             PdpSubGroup pdpSubGroup = new PdpSubGroup();
197             pdpSubGroup.setPdpType("type");
198             pdpSubGroup.setDesiredInstanceCount(123);
199             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
200             pdpSubGroup.getSupportedPolicyTypes()
201                     .add(new ToscaPolicyTypeIdentifier(POLICY_TYPE_NAME, POLICY_TYPE_VERSION));
202             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
203
204             Pdp pdp = new Pdp();
205             pdp.setInstanceId("type-0");
206             pdp.setMessage("Hello");
207             pdp.setPdpState(PdpState.ACTIVE);
208             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
209             pdpSubGroup.setPdpInstances(new ArrayList<>());
210             pdpSubGroup.getPdpInstances().add(pdp);
211
212             // Create Pdp Groups
213             assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
214                     .getDesiredInstanceCount());
215             assertEquals(1, databaseProvider.getPdpGroups("group").size());
216
217             // Create Policy Type
218             assertThatCode(() -> {
219                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder.decode(
220                         ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
221                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
222             }).doesNotThrowAnyException();
223
224             // Create Policy
225             assertThatCode(() -> {
226                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
227                 LegacyOperationalPolicy policyToCreate =
228                         standardCoder.decode(policyString, LegacyOperationalPolicy.class);
229                 LegacyOperationalPolicy policyCreated =
230                         operationalPolicyProvider.createOperationalPolicy(policyToCreate);
231                 assertEquals("operational.restart", policyCreated.getPolicyId());
232                 assertEquals("1", policyCreated.getPolicyVersion());
233                 assertFalse(policyCreated.getContent() == null);
234             }).doesNotThrowAnyException();
235
236             // Test fetchDeployedPolicies (deployedPolicyMap.isEmpty())==true
237             assertThatThrownBy(() -> {
238                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
239             })  .hasMessage("could not find policy with ID " + POLICY_NAME + " and type " + POLICY_TYPE_ID
240                     + " deployed in any pdp group");
241
242
243             // Update pdpSubGroup
244             pdpSubGroup.setPolicies(new ArrayList<>());
245             pdpSubGroup.getPolicies()
246                     .add(new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION + LEGACY_MINOR_PATCH_SUFFIX));
247             assertEquals(1,
248                     databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
249
250             // Test fetchDeployedPolicies
251             assertThatCode(() -> {
252                 operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
253             }).doesNotThrowAnyException();
254
255             // Test validateDeleteEligibility exception path(!pdpGroups.isEmpty())
256             assertThatThrownBy(() -> {
257                 operationalPolicyProvider.deleteOperationalPolicy(POLICY_NAME, POLICY_VERSION);
258             })  .hasMessageContaining("policy with ID " + POLICY_NAME + ":" + POLICY_VERSION
259                     + " cannot be deleted as it is deployed in pdp groups");
260         } catch (Exception exc) {
261             fail("Test should not throw an exception");
262         }
263     }
264
265     @Test
266     public void testCreateOperationalPolicy() {
267
268         assertThatThrownBy(() -> {
269             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
270             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
271             operationalPolicyProvider.createOperationalPolicy(policyToCreate);
272         }).hasMessage("policy type " + POLICY_TYPE_ID + " for policy " + POLICY_ID + " does not exist");
273
274         assertThatCode(() -> {
275             ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder.decode(
276                     ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
277             policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
278
279             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
280             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
281             LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
282             assertNotNull(createdPolicy);
283             assertEquals("operational.restart", createdPolicy.getPolicyId());
284             assertTrue(createdPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
285         }).doesNotThrowAnyException();
286     }
287
288     @Test
289     public void testDeleteOperationalPolicyException() {
290         String policyId = "operational.restart";
291         String policyVersion = "1";
292         String policyTypeVersion = "1.0.0";
293         String policyTypeId = "onap.policies.controlloop.Operational";
294         String legacyMinorPatchSuffix = ".0.0";
295
296         try (PolicyModelsProvider databaseProvider =
297                 new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
298             assertEquals(0, databaseProvider.getPdpGroups("name").size());
299             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
300
301             assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
302             assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
303
304             PdpGroup pdpGroup = new PdpGroup();
305             pdpGroup.setName("group");
306             pdpGroup.setVersion("1.2.3");
307             pdpGroup.setPdpGroupState(PdpState.ACTIVE);
308             pdpGroup.setPdpSubgroups(new ArrayList<>());
309             List<PdpGroup> groupList = new ArrayList<>();
310             groupList.add(pdpGroup);
311
312             PdpSubGroup pdpSubGroup = new PdpSubGroup();
313             pdpSubGroup.setPdpType("type");
314             pdpSubGroup.setDesiredInstanceCount(123);
315             pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
316             pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier(policyTypeId, policyTypeVersion));
317             pdpGroup.getPdpSubgroups().add(pdpSubGroup);
318
319             Pdp pdp = new Pdp();
320             pdp.setInstanceId("type-0");
321             pdp.setMessage("Hello");
322             pdp.setPdpState(PdpState.ACTIVE);
323             pdp.setHealthy(PdpHealthStatus.UNKNOWN);
324             pdpSubGroup.setPdpInstances(new ArrayList<>());
325             pdpSubGroup.getPdpInstances().add(pdp);
326
327             // Create Pdp Groups
328             assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
329                     .getDesiredInstanceCount());
330             assertEquals(1, databaseProvider.getPdpGroups("group").size());
331
332             // Create Policy Type
333             assertThatCode(() -> {
334                 ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder.decode(
335                         ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
336                 policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
337             }).doesNotThrowAnyException();
338
339             // Create Policy
340             assertThatCode(() -> {
341                 String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
342                 LegacyOperationalPolicy policyToCreate =
343                         standardCoder.decode(policyString, LegacyOperationalPolicy.class);
344                 LegacyOperationalPolicy createdPolicy =
345                         operationalPolicyProvider.createOperationalPolicy(policyToCreate);
346                 assertNotNull(createdPolicy);
347             }).doesNotThrowAnyException();
348
349             // Update pdpSubGroup
350             pdpSubGroup.setPolicies(new ArrayList<>());
351             pdpSubGroup.getPolicies().add(new ToscaPolicyIdentifier(policyId, policyVersion + legacyMinorPatchSuffix));
352             assertEquals(1,
353                     databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0).getPolicies().size());
354             assertThatThrownBy(() -> {
355                 operationalPolicyProvider.deleteOperationalPolicy(policyId, policyVersion);
356             }).hasMessageContaining("cannot be deleted as it is deployed in pdp groups");
357         } catch (Exception exc) {
358             fail("Test should not throw an exception");
359         }
360     }
361
362     @Test
363     public void testDeleteOperationalPolicy() {
364
365         assertThatThrownBy(() -> {
366             operationalPolicyProvider.deleteOperationalPolicy("dummy", null);
367         }).hasMessage("legacy policy version is not an integer");
368
369         assertThatThrownBy(() -> {
370             operationalPolicyProvider.deleteOperationalPolicy("dummy", "dummy");
371         }).hasMessage("legacy policy version is not an integer");
372
373         assertThatCode(() -> {
374             ToscaServiceTemplate policyTypeServiceTemplate = standardYamlCoder.decode(
375                     ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE), ToscaServiceTemplate.class);
376             policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
377
378             String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
379             LegacyOperationalPolicy policyToCreate = standardCoder.decode(policyString, LegacyOperationalPolicy.class);
380             LegacyOperationalPolicy createdPolicy = operationalPolicyProvider.createOperationalPolicy(policyToCreate);
381             assertNotNull(createdPolicy);
382
383             LegacyOperationalPolicy deletedPolicy =
384                     operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
385             assertNotNull(deletedPolicy);
386             assertEquals("operational.restart", deletedPolicy.getPolicyId());
387             assertTrue(deletedPolicy.getContent().startsWith("controlLoop%3A%0A%20%20version%3A%202.0.0%0A%20%20"));
388         }).doesNotThrowAnyException();
389
390         assertThatThrownBy(() -> {
391             operationalPolicyProvider.deleteOperationalPolicy("operational.restart", "1");
392         }).hasMessage("no policy found for policy: operational.restart:1");
393
394         assertThatCode(() -> {
395             policyTypeProvider.deletePolicyType("onap.policies.controlloop.Operational", "1.0.0");
396         }).doesNotThrowAnyException();
397     }
398 }