481192927adcce803893c7fab7e2b48910b83a2c
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.clamp.controlloop.runtime.commissioning.rest;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertNotNull;
27 import static org.junit.jupiter.api.Assertions.assertNull;
28 import static org.junit.jupiter.api.Assertions.assertTrue;
29
30 import java.util.List;
31 import java.util.Map;
32 import javax.ws.rs.client.Entity;
33 import javax.ws.rs.client.Invocation;
34 import javax.ws.rs.core.Response;
35 import org.junit.jupiter.api.AfterEach;
36 import org.junit.jupiter.api.BeforeAll;
37 import org.junit.jupiter.api.BeforeEach;
38 import org.junit.jupiter.api.Test;
39 import org.junit.jupiter.api.extension.ExtendWith;
40 import org.junit.jupiter.api.parallel.Execution;
41 import org.junit.jupiter.api.parallel.ExecutionMode;
42 import org.onap.policy.clamp.controlloop.models.messages.rest.commissioning.CommissioningResponse;
43 import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup;
44 import org.onap.policy.clamp.controlloop.runtime.util.rest.CommonRestController;
45 import org.onap.policy.common.utils.coder.YamlJsonTranslator;
46 import org.onap.policy.common.utils.resources.ResourceUtils;
47 import org.onap.policy.models.provider.PolicyModelsProvider;
48 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.boot.test.context.SpringBootTest;
53 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
54 import org.springframework.boot.web.server.LocalServerPort;
55 import org.springframework.test.context.TestPropertySource;
56 import org.springframework.test.context.junit.jupiter.SpringExtension;
57
58 @ExtendWith(SpringExtension.class)
59 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
60 @TestPropertySource(locations = {"classpath:application_test.properties"})
61 @Execution(ExecutionMode.SAME_THREAD)
62 class CommissioningControllerTest extends CommonRestController {
63
64     private static final String TOSCA_SERVICE_TEMPLATE_YAML =
65             "src/test/resources/rest/servicetemplates/pmsh_multiple_cl_tosca.yaml";
66     private static final String COMMON_TOSCA_SERVICE_TEMPLATE_YAML =
67         "src/test/resources/rest/servicetemplates/full-tosca-with-common-properties.yaml";
68     private static final YamlJsonTranslator yamlTranslator = new YamlJsonTranslator();
69     private static final String COMMISSIONING_ENDPOINT = "commission";
70     private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate();
71     private static ToscaServiceTemplate commonPropertiesServiceTemplate = new ToscaServiceTemplate();
72
73     @Autowired
74     private ClRuntimeParameterGroup clRuntimeParameterGroup;
75
76     @LocalServerPort
77     private int randomServerPort;
78
79     /**
80      * starts Main and inserts a commissioning template.
81      *
82      * @throws Exception if an error occurs
83      */
84     @BeforeAll
85     public static void setUpBeforeClass() throws Exception {
86
87         serviceTemplate = yamlTranslator.fromYaml(ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML),
88                 ToscaServiceTemplate.class);
89         commonPropertiesServiceTemplate = yamlTranslator.fromYaml(ResourceUtils
90                 .getResourceAsString(COMMON_TOSCA_SERVICE_TEMPLATE_YAML),
91             ToscaServiceTemplate.class);
92     }
93
94     @BeforeEach
95     public void setUpPort() {
96         super.setHttpPrefix(randomServerPort);
97     }
98
99     @AfterEach
100     public void cleanDatabase() throws Exception {
101         deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion());
102         deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion());
103     }
104
105     @Test
106     void testSwagger() throws Exception {
107         super.testSwagger(COMMISSIONING_ENDPOINT);
108     }
109
110     @Test
111     void testUnauthorizedCreate() throws Exception {
112         assertUnauthorizedPost(COMMISSIONING_ENDPOINT, Entity.json(serviceTemplate));
113     }
114
115     @Test
116     void testUnauthorizedQuery() throws Exception {
117         assertUnauthorizedGet(COMMISSIONING_ENDPOINT);
118     }
119
120     @Test
121     void testUnauthorizedQueryElements() throws Exception {
122         assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/elements");
123     }
124
125     @Test
126     void testUnauthorizedDelete() throws Exception {
127         assertUnauthorizedDelete(COMMISSIONING_ENDPOINT);
128     }
129
130     @Test
131     void testUnauthorizedQueryToscaServiceTemplate() throws Exception {
132         assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/toscaservicetemplate");
133     }
134
135     @Test
136     void testUnauthorizedQueryToscaServiceTemplateSchema() throws Exception {
137         assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/toscaServiceTemplateSchema");
138     }
139
140     @Test
141     void testUnauthorizedQueryToscaServiceCommonOrInstanceProperties() throws Exception {
142         assertUnauthorizedGet(COMMISSIONING_ENDPOINT + "/getCommonOrInstanceProperties");
143     }
144
145     @Test
146     void testQueryToscaServiceTemplate() throws Exception {
147         createFullEntryInDbWithCommonProps();
148
149         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT
150             + "/toscaservicetemplate");
151         Response rawresp = invocationBuilder.buildGet().invoke();
152         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
153         ToscaServiceTemplate template = rawresp.readEntity(ToscaServiceTemplate.class);
154         assertNotNull(template);
155         assertThat(template.getNodeTypes()).hasSize(8);
156
157     }
158
159     @Test
160     void testQueryToscaServiceTemplateSchema() throws Exception {
161         createFullEntryInDbWithCommonProps();
162
163         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT
164             + "/toscaServiceTemplateSchema");
165         Response rawresp = invocationBuilder.buildGet().invoke();
166         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
167         String schema = rawresp.readEntity(String.class);
168         assertNotNull(schema);
169
170     }
171
172     @Test
173     void testQueryCommonOrInstanceProperties() throws Exception {
174         createFullEntryInDbWithCommonProps();
175
176         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT
177             + "/getCommonOrInstanceProperties" + "?common=true&name=ToscaServiceTemplateSimple&version=1.0.0");
178         Response rawresp = invocationBuilder.buildGet().invoke();
179         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
180
181         @SuppressWarnings("unchecked")
182         Map<String, ToscaNodeTemplate> commonProperties = rawresp.readEntity(Map.class);
183
184         assertNotNull(commonProperties);
185         assertThat(commonProperties).hasSize(6);
186
187     }
188
189     @Test
190     void testCreateBadRequest() throws Exception {
191         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
192         Response resp = invocationBuilder.post(Entity.json("NotToscaServiceTempalte"));
193
194         assertThat(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).isEqualTo(resp.getStatus());
195         CommissioningResponse commissioningResponse = resp.readEntity(CommissioningResponse.class);
196         assertThat(commissioningResponse.getErrorDetails()).isNotNull();
197         assertThat(commissioningResponse.getAffectedControlLoopDefinitions()).isNull();
198     }
199
200     @Test
201     void testCreate() throws Exception {
202         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
203         Response resp = invocationBuilder.post(Entity.json(serviceTemplate));
204         assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
205         CommissioningResponse commissioningResponse = resp.readEntity(CommissioningResponse.class);
206
207         assertNotNull(commissioningResponse);
208         assertNull(commissioningResponse.getErrorDetails());
209         // Response should return the number of node templates present in the service template
210         assertThat(commissioningResponse.getAffectedControlLoopDefinitions()).hasSize(13);
211         for (String nodeTemplateName : serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().keySet()) {
212             assertTrue(commissioningResponse.getAffectedControlLoopDefinitions().stream()
213                     .anyMatch(ac -> ac.getName().equals(nodeTemplateName)));
214         }
215
216     }
217
218     @Test
219     void testQuery_NoResultWithThisName() throws Exception {
220         createEntryInDB();
221
222         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name=noResultWithThisName");
223         Response rawresp = invocationBuilder.buildGet().invoke();
224         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
225         List<?> entityList = rawresp.readEntity(List.class);
226         assertThat(entityList).isEmpty();
227
228     }
229
230     @Test
231     void testQuery() throws Exception {
232         createEntryInDB();
233
234         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
235         Response rawresp = invocationBuilder.buildGet().invoke();
236         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
237         List<?> entityList = rawresp.readEntity(List.class);
238         assertNotNull(entityList);
239         assertThat(entityList).hasSize(2);
240
241     }
242
243     @Test
244     void testQueryElementsBadRequest() throws Exception {
245         createEntryInDB();
246
247         //Call get elements with no info
248         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/elements");
249         Response resp = invocationBuilder.buildGet().invoke();
250         assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), resp.getStatus());
251
252     }
253
254     @Test
255     void testQueryElements() throws Exception {
256         createEntryInDB();
257
258         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "/elements"
259                 + "?name=org.onap.domain.pmsh.PMSHControlLoopDefinition");
260         Response rawresp = invocationBuilder.buildGet().invoke();
261         assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
262         List<?> entityList = rawresp.readEntity(List.class);
263         assertNotNull(entityList);
264         assertThat(entityList).hasSize(4);
265
266     }
267
268     @Test
269     void testDeleteBadRequest() throws Exception {
270         createEntryInDB();
271
272         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT);
273         //Call delete with no info
274         Response resp = invocationBuilder.delete();
275         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
276
277     }
278
279     @Test
280     void testDelete() throws Exception {
281         createEntryInDB();
282
283         Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name="
284                 + serviceTemplate.getName() + "&version=" + serviceTemplate.getVersion());
285         //Call delete with no info
286         Response resp = invocationBuilder.delete();
287         assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
288
289         try (PolicyModelsProvider modelsProvider = new PolicyModelsProviderFactory()
290                 .createPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters())) {
291             List<ToscaServiceTemplate> templatesInDB = modelsProvider.getServiceTemplateList(null, null);
292             assertThat(templatesInDB).isEmpty();
293         }
294
295     }
296
297     private synchronized void createEntryInDB() throws Exception {
298         try (PolicyModelsProvider modelsProvider = new PolicyModelsProviderFactory()
299                 .createPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters())) {
300             deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion());
301             modelsProvider.createServiceTemplate(serviceTemplate);
302         }
303     }
304
305     // Delete entries from the DB after relevant tests
306     private synchronized void deleteEntryInDB(String name, String version) throws Exception {
307         try (PolicyModelsProvider modelsProvider = new PolicyModelsProviderFactory()
308             .createPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters())) {
309             if (!modelsProvider.getServiceTemplateList(null, null).isEmpty()) {
310                 modelsProvider.deleteServiceTemplate(name, version);
311             }
312         }
313     }
314
315     private synchronized void createFullEntryInDbWithCommonProps() throws Exception {
316         try (PolicyModelsProvider modelsProvider = new PolicyModelsProviderFactory()
317             .createPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters())) {
318             deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion());
319             modelsProvider.createServiceTemplate(commonPropertiesServiceTemplate);
320         }
321     }
322 }