e6ecf5ade3c6dd2496466609103901e5d85e3c3d
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyLegacyOperationalPersistenceTest.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
29 import lombok.NonNull;
30
31 import org.junit.After;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.common.utils.coder.StandardCoder;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.onap.policy.models.base.PfModelException;
38 import org.onap.policy.models.provider.PolicyModelsProvider;
39 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
40 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
41 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
42 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.yaml.snakeyaml.Yaml;
46
47 /**
48  * Test persistence of monitoring policies to and from the database.
49  *
50  * @author Liam Fallon (liam.fallon@est.tech)
51  */
52 public class PolicyLegacyOperationalPersistenceTest {
53     // Logger for this class
54     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyLegacyOperationalPersistenceTest.class);
55
56     private StandardCoder standardCoder;
57
58     private PolicyModelsProvider databaseProvider;
59
60     // @formatter:off
61     private String[] policyInputResourceNames = {
62         "policies/vCPE.policy.operational.input.json",
63         "policies/vDNS.policy.operational.input.json",
64         "policies/vFirewall.policy.operational.input.json"
65     };
66
67     private String[] policyOutputResourceNames = {
68         "policies/vCPE.policy.operational.output.json",
69         "policies/vDNS.policy.operational.output.json",
70         "policies/vFirewall.policy.operational.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         LegacyOperationalPolicy lop = standardCoder.decode(policyInputString, LegacyOperationalPolicy.class);
133
134         assertNotNull(lop);
135
136         LegacyOperationalPolicy createdLop = databaseProvider.createOperationalPolicy(lop);
137         assertEquals(createdLop, lop);
138
139         LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId(), null);
140         assertEquals(gotLop, lop);
141
142         LegacyOperationalPolicy updatedLop = databaseProvider.updateOperationalPolicy(lop);
143         assertEquals(gotLop, updatedLop);
144
145         LegacyOperationalPolicy deletedLop = databaseProvider.deleteOperationalPolicy(lop.getPolicyId(), "1");
146         assertEquals(gotLop, deletedLop);
147
148         String actualRetrievedJson = standardCoder.encode(gotLop);
149
150         // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
151         assertEquals(
152                 policyOutputString.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", "'"),
153                 actualRetrievedJson.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_",
154                         "'"));
155     }
156
157     private void createPolicyTypes() throws CoderException, PfModelException {
158
159         Object yamlObject = new Yaml().load(
160                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.Operational.yaml"));
161         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
162
163         ToscaServiceTemplate toscaServiceTemplatePolicyType =
164                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
165
166         assertNotNull(toscaServiceTemplatePolicyType);
167         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
168     }
169 }