Add unit tests for policy type and policy filters
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyTypePersistenceTest.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 import java.util.List;
31
32 import lombok.NonNull;
33
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
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.ToscaPolicyType;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.yaml.snakeyaml.Yaml;
49
50 /**
51  * Test persistence of monitoring policies to and from the database.
52  *
53  * @author Liam Fallon (liam.fallon@est.tech)
54  */
55 public class PolicyTypePersistenceTest {
56     // Logger for this class
57     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyTypePersistenceTest.class);
58
59     private StandardCoder standardCoder;
60
61     private PolicyModelsProvider databaseProvider;
62
63     // @formatter:off
64     private String[] policyTypeResourceNames = {
65         "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
66         "policytypes/onap.policies.optimization.AffinityPolicy.yaml",
67         "policytypes/onap.policies.optimization.DistancePolicy.yaml",
68         "policytypes/onap.policies.optimization.HpaPolicy.yaml",
69         "policytypes/onap.policies.optimization.OptimizationPolicy.yaml",
70         "policytypes/onap.policies.optimization.PciPolicy.yaml",
71         "policytypes/onap.policies.optimization.QueryPolicy.yaml",
72         "policytypes/onap.policies.optimization.SubscriberPolicy.yaml",
73         "policytypes/onap.policies.optimization.Vim_fit.yaml",
74         "policytypes/onap.policies.optimization.VnfPolicy.yaml",
75         "policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml"
76     };
77     // @formatter:on
78
79     /**
80      * Initialize provider.
81      *
82      * @throws PfModelException on exceptions in the tests
83      */
84     @Before
85     public void setupParameters() throws PfModelException {
86         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
87         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
88         parameters.setDatabaseUser("policy");
89         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
90         parameters.setPersistenceUnit("ToscaConceptTest");
91
92         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
93     }
94
95     /**
96      * Set up GSON.
97      */
98     @Before
99     public void setupGson() {
100         standardCoder = new StandardCoder();
101     }
102
103     @After
104     public void teardown() throws Exception {
105         databaseProvider.close();
106     }
107
108     @Test
109     public void testPolicyPersistence() {
110         try {
111             for (String policyTypeResourceName : policyTypeResourceNames) {
112                 String policyTypeString = ResourceUtils.getResourceAsString(policyTypeResourceName);
113
114                 if (policyTypeResourceName.endsWith("yaml")) {
115                     testYamlStringPolicyTypePersistence(policyTypeString);
116                 } else {
117                     testJsonStringPolicyTypePersistence(policyTypeString);
118                 }
119             }
120         } catch (Exception exc) {
121             LOGGER.warn("error processing policies", exc);
122             fail("test should not throw an exception");
123         }
124     }
125
126     private void testYamlStringPolicyTypePersistence(final String policyTypeString) throws Exception {
127         Object yamlObject = new Yaml().load(policyTypeString);
128         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
129
130         testJsonStringPolicyTypePersistence(yamlAsJsonString);
131     }
132
133     /**
134      * Check persistence of a policy.
135      *
136      * @param policyTypeString the policy as a string
137      * @throws Exception any exception thrown
138      */
139     public void testJsonStringPolicyTypePersistence(@NonNull final String policyTypeString) throws Exception {
140         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyTypeString, ToscaServiceTemplate.class);
141
142         assertNotNull(serviceTemplate);
143         ToscaPolicyType inPolicyType = serviceTemplate.getPolicyTypes().get(0).values().iterator().next();
144
145         databaseProvider.createPolicyTypes(serviceTemplate);
146
147         List<ToscaPolicyType> policyTypeList =
148                 databaseProvider.getPolicyTypeList(inPolicyType.getName(), inPolicyType.getVersion());
149
150         policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder()
151                 .name(inPolicyType.getName()).version(inPolicyType.getVersion()).build());
152
153         assertEquals(1, policyTypeList.size());
154         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
155
156         policyTypeList = databaseProvider
157                 .getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().name(inPolicyType.getName()).build());
158
159         assertEquals(1, policyTypeList.size());
160         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
161
162         policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().build());
163         assertEquals(2, policyTypeList.size());
164         assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName());
165
166         for (ToscaPolicyType policyType: databaseProvider.getPolicyTypeList(null, null)) {
167             databaseProvider.deletePolicyType(policyType.getName(), policyType.getVersion());
168         }
169     }
170 }