ef83ea669b87510515f667b93755e4a887e7694c
[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 Exception {
82         // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
83
84         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
85         parameters.setDatabaseDriver("org.h2.Driver");
86         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
87         parameters.setDatabaseUser("policy");
88         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
89         parameters.setPersistenceUnit("ToscaConceptTest");
90
91         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
92
93         createPolicyTypes();
94     }
95
96     /**
97      * Set up standard coder.
98      */
99     @Before
100     public void setupStandardCoder() {
101         standardCoder = new StandardCoder();
102     }
103
104     @After
105     public void teardown() throws Exception {
106         databaseProvider.close();
107     }
108
109     @Test
110     public void testPolicyPersistence() {
111         try {
112             for (int i = 0; i < policyInputResourceNames.length; i++) {
113                 String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]);
114                 String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]);
115                 testJsonStringPolicyPersistence(policyInputString, policyOutputString);
116             }
117         } catch (Exception exc) {
118             LOGGER.warn("error processing policies", exc);
119             fail("test should not throw an exception");
120         }
121     }
122
123     /**
124      * Check persistence of a policy.
125      *
126      * @param policyInputString the policy as a string
127      * @param policyOutputString the expected output string
128      * @throws Exception any exception thrown
129      */
130     public void testJsonStringPolicyPersistence(@NonNull final String policyInputString,
131             final String policyOutputString) throws Exception {
132         LegacyGuardPolicyInput gip = standardCoder.decode(policyInputString, LegacyGuardPolicyInput.class);
133
134         assertNotNull(gip);
135
136         Map<String, LegacyGuardPolicyOutput> createdGopm = databaseProvider.createGuardPolicy(gip);
137         assertEquals(gip.getPolicyId(), createdGopm.keySet().iterator().next());
138         assertEquals(gip.getContent(),
139                 createdGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
140
141         Map<String, LegacyGuardPolicyOutput> gotGopm = databaseProvider.getGuardPolicy(gip.getPolicyId(), null);
142         assertEquals(gip.getPolicyId(), gotGopm.keySet().iterator().next());
143         assertEquals(gip.getContent(),
144                 gotGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
145
146         Map<String, LegacyGuardPolicyOutput> updatedGopm = databaseProvider.updateGuardPolicy(gip);
147         assertEquals(gip.getPolicyId(), updatedGopm.keySet().iterator().next());
148         assertEquals(gip.getContent(),
149                 updatedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
150
151         Map<String, LegacyGuardPolicyOutput> deletedGopm = databaseProvider.deleteGuardPolicy(gip.getPolicyId(), "1");
152         assertEquals(gip.getPolicyId(), deletedGopm.keySet().iterator().next());
153         assertEquals(gip.getContent(),
154                 deletedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
155
156         String actualRetrievedJson = standardCoder.encode(gotGopm);
157
158         // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
159         assertEquals(policyOutputString.replaceAll("\\s+", ""), actualRetrievedJson.replaceAll("\\s+", ""));
160     }
161
162     private void createPolicyTypes() throws CoderException, PfModelException {
163         Object yamlObject = new Yaml().load(
164                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml"));
165         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
166
167         ToscaServiceTemplate toscaServiceTemplatePolicyType =
168                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
169
170         assertNotNull(toscaServiceTemplatePolicyType);
171         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
172
173         yamlObject = new Yaml().load(
174                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.MinMax.yaml"));
175         yamlAsJsonString = new StandardCoder().encode(yamlObject);
176
177         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
178
179         assertNotNull(toscaServiceTemplatePolicyType);
180         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
181     }
182 }