Store policy type version in policy before DB write
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyPersistenceTest.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.fail;
26
27 import com.google.gson.GsonBuilder;
28
29 import java.util.Base64;
30 import java.util.Map;
31
32 import lombok.NonNull;
33
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.onap.policy.common.utils.coder.CoderException;
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.ToscaPolicy;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
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 PolicyPersistenceTest {
57     // Logger for this class
58     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyPersistenceTest.class);
59
60     private StandardCoder standardCoder;
61
62     private PolicyModelsProvider databaseProvider;
63
64     // @formatter:off
65     private String[] policyResourceNames = {
66         "policies/vCPE.policy.monitoring.input.tosca.json",
67         "policies/vCPE.policy.monitoring.input.tosca.yaml",
68         "policies/vCPE.policy.operational.input.tosca.yaml",
69         "policies/vDNS.policy.guard.frequency.input.tosca.json",
70         "policies/vDNS.policy.guard.frequency.input.tosca.yaml",
71         "policies/vDNS.policy.monitoring.input.tosca.json",
72         "policies/vDNS.policy.monitoring.input.tosca.yaml",
73         "policies/vDNS.policy.operational.input.tosca.yaml",
74         "policies/vFirewall.policy.monitoring.input.tosca.json",
75         "policies/vFirewall.policy.monitoring.input.tosca.yaml",
76         "policies/vFirewall.policy.operational.input.tosca.json",
77         "policies/vFirewall.policy.operational.input.tosca.yaml"
78     };
79     // @formatter:on
80
81     /**
82      * Initialize provider.
83      *
84      * @throws PfModelException on exceptions in the tests
85      * @throws CoderException on JSON encoding and decoding errors
86      */
87     @Before
88     public void setupParameters() throws PfModelException, CoderException {
89         // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
90
91         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
92         parameters.setDatabaseDriver("org.h2.Driver");
93         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
94         parameters.setDatabaseUser("policy");
95         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
96         parameters.setPersistenceUnit("ToscaConceptTest");
97
98         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
99
100         createPolicyTypes();
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 testPolicyPersistence() {
118         try {
119             for (String policyResourceName : policyResourceNames) {
120                 String policyString = ResourceUtils.getResourceAsString(policyResourceName);
121
122                 if (policyResourceName.endsWith("yaml")) {
123                     testYamlStringPolicyPersistence(policyString);
124                 } else {
125                     testJsonStringPolicyPersistence(policyString);
126                 }
127             }
128         } catch (Exception exc) {
129             LOGGER.warn("error processing policies", exc);
130             fail("test should not throw an exception");
131         }
132     }
133
134     private void testYamlStringPolicyPersistence(final String policyString) throws Exception {
135         Object yamlObject = new Yaml().load(policyString);
136         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
137
138         testJsonStringPolicyPersistence(yamlAsJsonString);
139     }
140
141     /**
142      * Check persistence of a policy.
143      *
144      * @param policyString the policy as a string
145      * @throws Exception any exception thrown
146      */
147     public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception {
148         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class);
149
150         assertNotNull(serviceTemplate);
151
152         databaseProvider.createPolicies(serviceTemplate);
153         databaseProvider.updatePolicies(serviceTemplate);
154
155         for (Map<String, ToscaPolicy> policyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
156             for (ToscaPolicy policy : policyMap.values()) {
157                 ToscaServiceTemplate gotToscaServiceTemplate =
158                         databaseProvider.getPolicies(policy.getName(), policy.getVersion());
159
160                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
161                         .get(policy.getName()).getType(), policy.getType());
162
163                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build());
164
165                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
166                         .get(policy.getName()).getType(), policy.getType());
167
168                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(
169                         ToscaPolicyFilter.builder().name(policy.getName()).version(policy.getVersion()).build());
170
171                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
172                         .get(policy.getName()).getType(), policy.getType());
173             }
174         }
175     }
176
177     private void createPolicyTypes() throws CoderException, PfModelException {
178         Object yamlObject = new Yaml().load(
179                 ResourceUtils.getResourceAsString("policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml"));
180         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
181
182         ToscaServiceTemplate toscaServiceTemplatePolicyType =
183                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
184
185         assertNotNull(toscaServiceTemplatePolicyType);
186         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
187
188         yamlObject = new Yaml().load(
189                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.Operational.yaml"));
190         yamlAsJsonString = new StandardCoder().encode(yamlObject);
191
192         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
193
194         assertNotNull(toscaServiceTemplatePolicyType);
195         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
196
197         yamlObject = new Yaml().load(
198                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml"));
199         yamlAsJsonString = new StandardCoder().encode(yamlObject);
200
201         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
202
203         assertNotNull(toscaServiceTemplatePolicyType);
204         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
205     }
206 }