Refactor optimization policies
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyTypePersistenceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.models.provider.impl;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import com.google.gson.GsonBuilder;
29
30 import java.util.Base64;
31 import java.util.List;
32
33 import lombok.NonNull;
34
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.onap.policy.common.utils.coder.StandardCoder;
39 import org.onap.policy.common.utils.resources.ResourceUtils;
40 import org.onap.policy.models.base.PfModelException;
41 import org.onap.policy.models.provider.PolicyModelsProvider;
42 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
43 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.yaml.snakeyaml.Yaml;
50
51 /**
52  * Test persistence of monitoring policies to and from the database.
53  *
54  * @author Liam Fallon (liam.fallon@est.tech)
55  */
56 public class PolicyTypePersistenceTest {
57     // Logger for this class
58     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyTypePersistenceTest.class);
59
60     private StandardCoder standardCoder;
61
62     private PolicyModelsProvider databaseProvider;
63
64     // @formatter:off
65     private String[] policyTypeResourceNames = {
66         "policytypes/onap.policies.controlloop.Operational.yaml",
67         "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
68         "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml",
69         "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
70         "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
71         "policytypes/onap.policies.controlloop.guard.Blacklist.yaml",
72         "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
73         "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
74         "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
75         "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
76         "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
77         "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
78         "policytypes/onap.policies.controlloop.guard.MinMax.yaml",
79         "policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml",
80         "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
81         "policytypes/onap.policies.Optimization.yaml",
82         "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml"
83     };
84     // @formatter:on
85
86     /**
87      * Initialize provider.
88      *
89      * @throws PfModelException on exceptions in the tests
90      */
91     @Before
92     public void setupParameters() throws PfModelException {
93         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
94         parameters.setDatabaseDriver("org.h2.Driver");
95         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
96         parameters.setDatabaseUser("policy");
97         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
98         parameters.setPersistenceUnit("ToscaConceptTest");
99
100         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
101     }
102
103     /**
104      * Set up GSON.
105      */
106     @Before
107     public void setupGson() {
108         standardCoder = new StandardCoder();
109     }
110
111     @After
112     public void teardown() throws Exception {
113         databaseProvider.close();
114     }
115
116     @Test
117     public void testPolicyTypePersistence() {
118         try {
119             for (String policyTypeResourceName : policyTypeResourceNames) {
120                 String policyTypeString = ResourceUtils.getResourceAsString(policyTypeResourceName);
121
122                 if (policyTypeResourceName.endsWith("yaml")) {
123                     testYamlStringPolicyTypePersistence(policyTypeString);
124                 } else {
125                     testJsonStringPolicyTypePersistence(policyTypeString);
126                 }
127             }
128         } catch (Exception exc) {
129             LOGGER.warn("error processing policy types", exc);
130             fail("test should not throw an exception");
131         }
132     }
133
134     private void testYamlStringPolicyTypePersistence(final String policyTypeString) throws Exception {
135         Object yamlObject = new Yaml().load(policyTypeString);
136         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
137
138         testJsonStringPolicyTypePersistence(yamlAsJsonString);
139     }
140
141     /**
142      * Check persistence of a policy.
143      *
144      * @param policyTypeString the policy as a string
145      * @throws Exception any exception thrown
146      */
147     public void testJsonStringPolicyTypePersistence(@NonNull final String policyTypeString) throws Exception {
148         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyTypeString, ToscaServiceTemplate.class);
149
150         assertNotNull(serviceTemplate);
151         ToscaPolicyType inPolicyType = serviceTemplate.getPolicyTypes().values().iterator().next();
152
153         databaseProvider.createPolicyTypes(serviceTemplate);
154         databaseProvider.updatePolicyTypes(serviceTemplate);
155
156         List<ToscaPolicyType> policyTypeList =
157                 databaseProvider.getPolicyTypeList(inPolicyType.getName(), inPolicyType.getVersion());
158
159         policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder()
160                 .name(inPolicyType.getName()).version(inPolicyType.getVersion()).build());
161
162         assertEquals(1, policyTypeList.size());
163         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
164
165         policyTypeList = databaseProvider
166                 .getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().name(inPolicyType.getName()).build());
167
168         assertEquals(1, policyTypeList.size());
169         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
170
171         policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().build());
172         assertTrue(policyTypeList.size() <= 3);
173         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
174
175         for (ToscaPolicyType policyType: databaseProvider.getPolicyTypeList(null, null)) {
176             databaseProvider.deletePolicyType(policyType.getName(), policyType.getVersion());
177         }
178     }
179 }