Set default and check existance of Policy Type
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyLegacyGuardPersistenceTest.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 java.util.Base64;
28 import java.util.Map;
29
30 import lombok.NonNull;
31
32 import org.junit.After;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.onap.policy.common.utils.coder.CoderException;
36 import org.onap.policy.common.utils.coder.StandardCoder;
37 import org.onap.policy.common.utils.resources.ResourceUtils;
38 import org.onap.policy.models.base.PfModelException;
39 import org.onap.policy.models.provider.PolicyModelsProvider;
40 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
41 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
43 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
44 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
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 PolicyLegacyGuardPersistenceTest {
55     // Logger for this class
56     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyLegacyGuardPersistenceTest.class);
57
58     private StandardCoder standardCoder;
59
60     private PolicyModelsProvider databaseProvider;
61
62     // @formatter:off
63     private String[] policyInputResourceNames = {
64         "policies/vDNS.policy.guard.frequency.input.json",
65         "policies/vDNS.policy.guard.minmax.input.json"
66     };
67
68     private String[] policyOutputResourceNames = {
69         "policies/vDNS.policy.guard.frequency.output.json",
70         "policies/vDNS.policy.guard.minmax.output.json"
71     };
72     // @formatter:on
73
74     /**
75      * Initialize provider.
76      *
77      * @throws PfModelException on exceptions in the tests
78      * @throws CoderException on JSON encoding and decoding errors
79      */
80     @Before
81     public void setupParameters() throws PfModelException, CoderException {
82         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
83         parameters.setDatabaseDriver("org.h2.Driver");
84         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
85         parameters.setDatabaseUser("policy");
86         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
87         parameters.setPersistenceUnit("ToscaConceptTest");
88
89         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
90
91         createPolicyTypes();
92     }
93
94     /**
95      * Set up standard coder.
96      */
97     @Before
98     public void setupStandardCoder() {
99         standardCoder = new StandardCoder();
100     }
101
102     @After
103     public void teardown() throws Exception {
104         databaseProvider.close();
105     }
106
107     @Test
108     public void testPolicyPersistence() {
109         try {
110             for (int i = 0; i < policyInputResourceNames.length; i++) {
111                 String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]);
112                 String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]);
113                 testJsonStringPolicyPersistence(policyInputString, policyOutputString);
114             }
115         } catch (Exception exc) {
116             LOGGER.warn("error processing policies", exc);
117             fail("test should not throw an exception");
118         }
119     }
120
121     /**
122      * Check persistence of a policy.
123      *
124      * @param policyInputString the policy as a string
125      * @param policyOutputString the expected output string
126      * @throws Exception any exception thrown
127      */
128     public void testJsonStringPolicyPersistence(@NonNull final String policyInputString,
129             final String policyOutputString) throws Exception {
130         LegacyGuardPolicyInput gip = standardCoder.decode(policyInputString, LegacyGuardPolicyInput.class);
131
132         assertNotNull(gip);
133
134         Map<String, LegacyGuardPolicyOutput> createdGopm = databaseProvider.createGuardPolicy(gip);
135         assertEquals(gip.getPolicyId(), createdGopm.keySet().iterator().next());
136         assertEquals(gip.getContent(),
137                 createdGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
138
139         Map<String, LegacyGuardPolicyOutput> gotGopm = databaseProvider.getGuardPolicy(gip.getPolicyId());
140         assertEquals(gip.getPolicyId(), gotGopm.keySet().iterator().next());
141         assertEquals(gip.getContent(),
142                 gotGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
143
144         Map<String, LegacyGuardPolicyOutput> updatedGopm = databaseProvider.updateGuardPolicy(gip);
145         assertEquals(gip.getPolicyId(), updatedGopm.keySet().iterator().next());
146         assertEquals(gip.getContent(),
147                 updatedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
148
149         Map<String, LegacyGuardPolicyOutput> deletedGopm = databaseProvider.deleteGuardPolicy(gip.getPolicyId());
150         assertEquals(gip.getPolicyId(), deletedGopm.keySet().iterator().next());
151         assertEquals(gip.getContent(),
152                 deletedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
153
154         String actualRetrievedJson = standardCoder.encode(gotGopm);
155
156         // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
157         assertEquals(policyOutputString.replaceAll("\\s+", ""), actualRetrievedJson.replaceAll("\\s+", ""));
158     }
159
160     private void createPolicyTypes() throws CoderException, PfModelException {
161         Object yamlObject = new Yaml().load(
162                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml"));
163         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
164
165         ToscaServiceTemplate toscaServiceTemplatePolicyType =
166                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
167
168         assertNotNull(toscaServiceTemplatePolicyType);
169         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
170
171         yamlObject = new Yaml().load(
172                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.MinMax.yaml"));
173         yamlAsJsonString = new StandardCoder().encode(yamlObject);
174
175         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
176
177         assertNotNull(toscaServiceTemplatePolicyType);
178         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
179     }
180 }