Set default and check existance of Policy Type
[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 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         LegacyOperationalPolicy lop = standardCoder.decode(policyInputString, LegacyOperationalPolicy.class);
131
132         assertNotNull(lop);
133
134         LegacyOperationalPolicy createdLop = databaseProvider.createOperationalPolicy(lop);
135         assertEquals(createdLop, lop);
136
137         LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId());
138         assertEquals(gotLop, lop);
139
140         LegacyOperationalPolicy updatedLop = databaseProvider.updateOperationalPolicy(lop);
141         assertEquals(gotLop, updatedLop);
142
143         LegacyOperationalPolicy deletedLop = databaseProvider.deleteOperationalPolicy(lop.getPolicyId());
144         assertEquals(gotLop, deletedLop);
145
146         String actualRetrievedJson = standardCoder.encode(gotLop);
147
148         // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
149         assertEquals(
150                 policyOutputString.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", "'"),
151                 actualRetrievedJson.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_",
152                         "'"));
153     }
154
155     private void createPolicyTypes() throws CoderException, PfModelException {
156
157         Object yamlObject = new Yaml().load(
158                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.Operational.yaml"));
159         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
160
161         ToscaServiceTemplate toscaServiceTemplatePolicyType =
162                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
163
164         assertNotNull(toscaServiceTemplatePolicyType);
165         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
166     }
167 }