Set default and check existance of Policy Type
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyToscaPersistenceTest.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
31 import lombok.NonNull;
32
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.ResourceUtils;
39 import org.onap.policy.models.base.PfModelException;
40 import org.onap.policy.models.provider.PolicyModelsProvider;
41 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
42 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.yaml.snakeyaml.Yaml;
48
49 /**
50  * Test persistence of monitoring policies to and from the database.
51  *
52  * @author Liam Fallon (liam.fallon@est.tech)
53  */
54 public class PolicyToscaPersistenceTest {
55     // Logger for this class
56     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyToscaPersistenceTest.class);
57
58     private StandardCoder standardCoder;
59
60     private PolicyModelsProvider databaseProvider;
61
62     // @formatter:off
63     private String[] policyResourceNames = {
64         "policies/vCPE.policy.monitoring.input.tosca.json",
65         "policies/vCPE.policy.monitoring.input.tosca.yaml",
66         "policies/vCPE.policy.operational.input.tosca.yaml",
67         "policies/vDNS.policy.guard.frequency.input.tosca.json",
68         "policies/vDNS.policy.guard.frequency.input.tosca.yaml",
69         "policies/vDNS.policy.monitoring.input.tosca.json",
70         "policies/vDNS.policy.monitoring.input.tosca.yaml",
71         "policies/vDNS.policy.operational.input.tosca.yaml",
72         "policies/vFirewall.policy.monitoring.input.tosca.json",
73         "policies/vFirewall.policy.monitoring.input.tosca.yaml",
74         "policies/vFirewall.policy.operational.input.tosca.json",
75         "policies/vFirewall.policy.operational.input.tosca.yaml"
76     };
77     // @formatter:on
78
79     /**
80      * Initialize provider.
81      *
82      * @throws PfModelException on exceptions in the tests
83      * @throws CoderException on JSON encoding and decoding errors
84      */
85     @Before
86     public void setupParameters() throws PfModelException, CoderException {
87         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
88         parameters.setDatabaseDriver("org.h2.Driver");
89         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
90         parameters.setDatabaseUser("policy");
91         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
92         parameters.setPersistenceUnit("ToscaConceptTest");
93
94         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
95
96         createPolicyTypes();
97     }
98
99     /**
100      * Set up the standard coder.
101      */
102     @Before
103     public void setupStandardCoder() {
104         standardCoder = new StandardCoder();
105     }
106
107     @After
108     public void teardown() throws Exception {
109         databaseProvider.close();
110     }
111
112     @Test
113     public void testPolicyPersistence() {
114         try {
115             for (String policyResourceName : policyResourceNames) {
116                 String policyString = ResourceUtils.getResourceAsString(policyResourceName);
117
118                 if (policyResourceName.endsWith("yaml")) {
119                     testYamlStringPolicyPersistence(policyString);
120                 } else {
121                     testJsonStringPolicyPersistence(policyString);
122                 }
123             }
124         } catch (Exception exc) {
125             LOGGER.warn("error processing policy types", exc);
126             fail("test should not throw an exception");
127         }
128     }
129
130     private void testYamlStringPolicyPersistence(final String policyString) throws Exception {
131         Object yamlObject = new Yaml().load(policyString);
132         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
133
134         testJsonStringPolicyPersistence(yamlAsJsonString);
135     }
136
137     /**
138      * Check persistence of a policy.
139      *
140      * @param policyString the policy as a string
141      * @throws Exception any exception thrown
142      */
143     public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception {
144         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class);
145
146         assertNotNull(serviceTemplate);
147
148         databaseProvider.createPolicies(serviceTemplate);
149
150         for (String policyKey : serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).keySet()) {
151             ToscaPolicy incomingPolicy = serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey);
152             ToscaPolicy databasePolicy =
153                     databaseProvider.getPolicies(incomingPolicy.getName(), incomingPolicy.getVersion())
154                             .getToscaTopologyTemplate().getPolicies().get(0).get(policyKey);
155             assertEquals(incomingPolicy.getType(), databasePolicy.getType());
156         }
157     }
158
159     private void createPolicyTypes() throws CoderException, PfModelException {
160         Object yamlObject = new Yaml().load(
161                 ResourceUtils.getResourceAsString("policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml"));
162         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
163
164         ToscaServiceTemplate toscaServiceTemplatePolicyType =
165                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
166
167         assertNotNull(toscaServiceTemplatePolicyType);
168         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
169
170         yamlObject = new Yaml().load(
171                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.Operational.yaml"));
172         yamlAsJsonString = new StandardCoder().encode(yamlObject);
173
174         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
175
176         assertNotNull(toscaServiceTemplatePolicyType);
177         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
178
179         yamlObject = new Yaml().load(
180                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml"));
181         yamlAsJsonString = new StandardCoder().encode(yamlObject);
182
183         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
184
185         assertNotNull(toscaServiceTemplatePolicyType);
186         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
187     }
188 }