Read resource dirs in models prvider unit tests
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyToscaPersistenceTest.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
26 import com.google.gson.GsonBuilder;
27
28 import java.net.URISyntaxException;
29 import java.util.Base64;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33
34 import lombok.NonNull;
35
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardCoder;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42 import org.onap.policy.models.base.PfModelException;
43 import org.onap.policy.models.provider.PolicyModelsProvider;
44 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
45 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
49 import org.yaml.snakeyaml.Yaml;
50
51 /**
52  * Test persistence of monitoring policies to and from the database.
53  *
54  * @author Liam Fallon (liam.fallon@est.tech)
55  */
56 public class PolicyToscaPersistenceTest {
57     private StandardCoder standardCoder;
58
59     private PolicyModelsProvider databaseProvider;
60
61     /**
62      * Initialize provider.
63      *
64      * @throws PfModelException on exceptions in the tests
65      * @throws CoderException on JSON encoding and decoding errors
66      */
67     @Before
68     public void setupParameters() throws Exception {
69         // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
70
71         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
72         parameters.setDatabaseDriver("org.h2.Driver");
73         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
74         parameters.setDatabaseUser("policy");
75         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
76         parameters.setPersistenceUnit("ToscaConceptTest");
77
78         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
79
80         createPolicyTypes();
81     }
82
83     /**
84      * Set up standard coder.
85      */
86     @Before
87     public void setupStandardCoder() {
88         standardCoder = new StandardCoder();
89     }
90
91     @After
92     public void teardown() throws Exception {
93         databaseProvider.close();
94     }
95
96     @Test
97     public void testPolicyPersistence() throws Exception {
98         Set<String> policyResources = ResourceUtils.getDirectoryContents("policies");
99
100         for (String policyResource : policyResources) {
101             if (!policyResource.contains("\\.tosca\\.")) {
102                 continue;
103             }
104
105             String policyString = ResourceUtils.getResourceAsString(policyResource);
106
107             if (policyResource.endsWith("yaml")) {
108                 testYamlStringPolicyPersistence(policyString);
109             } else {
110                 testJsonStringPolicyPersistence(policyString);
111             }
112         }
113     }
114
115     private void testYamlStringPolicyPersistence(final String policyString) throws Exception {
116         Object yamlObject = new Yaml().load(policyString);
117         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
118
119         testJsonStringPolicyPersistence(yamlAsJsonString);
120     }
121
122     /**
123      * Check persistence of a policy.
124      *
125      * @param policyString the policy as a string
126      * @throws Exception any exception thrown
127      */
128     public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception {
129         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class);
130
131         assertNotNull(serviceTemplate);
132
133         databaseProvider.createPolicies(serviceTemplate);
134         databaseProvider.updatePolicies(serviceTemplate);
135
136         for (Map<String, ToscaPolicy> policyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
137             for (ToscaPolicy policy : policyMap.values()) {
138                 ToscaServiceTemplate gotToscaServiceTemplate =
139                         databaseProvider.getPolicies(policy.getName(), policy.getVersion());
140
141                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
142                         .get(policy.getName()).getType(), policy.getType());
143
144                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build());
145
146                 assertEquals(getToscaPolicyFromMapList(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies(),
147                         policy.getName()).getType(), policy.getType());
148
149                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(
150                         ToscaPolicyFilter.builder().name(policy.getName()).version(policy.getVersion()).build());
151
152                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
153                         .get(policy.getName()).getType(), policy.getType());
154             }
155         }
156     }
157
158     private ToscaPolicy getToscaPolicyFromMapList(List<Map<String, ToscaPolicy>> toscaPolicyMapList,
159             String policyName) {
160         ToscaPolicy toscaPolicy = new ToscaPolicy();
161         for (Map<String, ToscaPolicy> policyMap : toscaPolicyMapList) {
162             if (policyMap.get(policyName) != null) {
163                 toscaPolicy = policyMap.get(policyName);
164                 break;
165             }
166         }
167         return toscaPolicy;
168     }
169
170     private void createPolicyTypes() throws CoderException, PfModelException, URISyntaxException {
171         Set<String> policyTypeResources = ResourceUtils.getDirectoryContents("policytypes");
172
173         for (String policyTyoeResource : policyTypeResources) {
174             Object yamlObject = new Yaml().load(ResourceUtils.getResourceAsString(policyTyoeResource));
175             String yamlAsJsonString = new StandardCoder().encode(yamlObject);
176
177             ToscaServiceTemplate toscaServiceTemplatePolicyType =
178                     standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
179
180             assertNotNull(toscaServiceTemplatePolicyType);
181             databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
182         }
183     }
184 }