Fix locally failing TCs in catalog-be
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / servlets / PolicyServletTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.servlets;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.Assert.assertEquals;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.ArgumentMatchers.anyMap;
27 import static org.mockito.ArgumentMatchers.anyString;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.when;
30 import static org.openecomp.sdc.common.api.Constants.GET_POLICY;
31
32 import com.fasterxml.jackson.databind.DeserializationFeature;
33 import fj.data.Either;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Objects;
39 import javax.ws.rs.client.ClientBuilder;
40 import javax.ws.rs.client.Entity;
41 import javax.ws.rs.client.Invocation;
42 import javax.ws.rs.core.GenericType;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.Response;
45 import org.glassfish.grizzly.http.util.HttpStatus;
46 import org.glassfish.jersey.client.ClientConfig;
47 import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
48 import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
49 import org.glassfish.jersey.server.ResourceConfig;
50 import org.glassfish.jersey.test.TestProperties;
51 import org.json.simple.JSONObject;
52 import org.junit.jupiter.api.AfterEach;
53 import org.junit.jupiter.api.BeforeAll;
54 import org.junit.jupiter.api.BeforeEach;
55 import org.junit.jupiter.api.Test;
56 import org.mockito.ArgumentCaptor;
57 import org.mockito.Captor;
58 import org.mockito.Mockito;
59 import org.mockito.Spy;
60 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
61 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
62 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
63 import org.openecomp.sdc.be.components.impl.aaf.RoleAuthorizationHandler;
64 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
65 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
66 import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator;
67 import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
68 import org.openecomp.sdc.be.config.ConfigurationManager;
69 import org.openecomp.sdc.be.dao.api.ActionStatus;
70 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
72 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
73 import org.openecomp.sdc.be.impl.ComponentsUtils;
74 import org.openecomp.sdc.be.impl.ServletUtils;
75 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
76 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
77 import org.openecomp.sdc.be.model.PolicyDefinition;
78 import org.openecomp.sdc.be.model.PolicyTargetDTO;
79 import org.openecomp.sdc.be.model.PropertyDefinition;
80 import org.openecomp.sdc.be.model.Service;
81 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
84 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
85 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
86 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
87 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
88 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
90 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
91 import org.openecomp.sdc.common.api.ConfigurationSource;
92 import org.openecomp.sdc.common.api.Constants;
93 import org.openecomp.sdc.common.api.FilterDecisionEnum;
94 import org.openecomp.sdc.common.impl.ExternalConfiguration;
95 import org.openecomp.sdc.common.impl.FSConfigurationSource;
96 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
97 import org.openecomp.sdc.exception.ResponseFormat;
98
99 class PolicyServletTest extends JerseySpringBaseTest {
100
101     private final static String USER_ID = "jh0003";
102     private static final String COMPONENT_ID = "componentId";
103     private static PolicyBusinessLogic businessLogic;
104     private static ComponentsUtils componentsUtils;
105     private static ServletUtils servletUtils;
106     private static PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
107     private static ToscaOperationFacade toscaOperationFacade;
108     private static RoleAuthorizationHandler roleAuthorizationHandler;
109     private static ResponseFormat responseFormat;
110     @Captor
111     private static ArgumentCaptor<PolicyDefinition> policyCaptor;
112     @Spy
113     private static BaseBusinessLogic baseBusinessLogic;
114
115     private static String validComponentType = "resources";
116     private static String unsupportedComponentType = "unsupported";
117     private static String componentId = "componentId";
118     private static String policyTypeName = "policyTypeName";
119
120     private static final String PROPS_URL = "/v1/catalog/{componentType}/{serviceId}/policies/{policyId}/properties";
121     private static final String DECLARE_URL = "v1/catalog/{componentType}/{serviceId}/create/policies";
122     private static final String DELETE_URL = "v1/catalog/{containerComponentType}/{componentId}/policies/{policyId}";
123     private static final String SERVICE_ID = "serviceId";
124     private static final String POLICY_ID = "policyId";
125     private static final String PROP_1 = "prop1";
126
127     private static final String UPDATE_TARGETS_URL = "/v1/catalog/{componentType}/{componentId}/policies/{policyId}/targets";
128     static ConfigurationSource configurationSource = new FSConfigurationSource(
129         ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
130     static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
131
132     @BeforeAll
133     public static void initClass() {
134         ResponseFormatManager.getInstance();
135         createMocks();
136         when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
137     }
138
139     @BeforeEach
140     public void before() throws Exception {
141         super.setUp();
142         Mockito.reset(businessLogic);
143         final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
144             .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
145         setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider)));
146         ThreadLocalsHolder.setApiType(FilterDecisionEnum.EXTERNAL);
147         when(request.isUserInRole(anyString())).thenReturn(true);
148
149     }
150
151     @AfterEach
152     void after() throws Exception {
153         super.tearDown();
154     }
155
156     @Test
157     void testGetPolicySuccess() {
158         String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
159         PolicyDefinition successResponse = new PolicyDefinition();
160         when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID)))
161             .thenReturn(successResponse);
162         Response response = target()
163             .path(path)
164             .request(MediaType.APPLICATION_JSON)
165             .header("USER_ID", USER_ID)
166             .get(Response.class);
167
168         assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
169     }
170
171     @Test
172     void testGetPolicyFailure() {
173         String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
174         Response response = target()
175             .path(path)
176             .request(MediaType.APPLICATION_JSON)
177             .header("USER_ID", USER_ID)
178             .get(Response.class);
179
180         assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
181     }
182
183     @Test
184     void testPostPolicySuccess() {
185         String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName;
186         PolicyDefinition policy = new PolicyDefinition();
187         PolicyDefinition successResponse = policy;
188         when(businessLogic
189             .createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true)))
190             .thenReturn(successResponse);
191         when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode());
192         when(componentsUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat);
193         Response response = target()
194             .path(path)
195             .request(MediaType.APPLICATION_JSON)
196             .header("USER_ID", USER_ID)
197             .post(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
198
199         assertEquals(response.getStatus(), HttpStatus.CREATED_201.getStatusCode());
200     }
201
202     @Test
203     void testPostPolicyFailure() {
204         String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName;
205         PolicyDefinition policy = new PolicyDefinition();
206         Response response = target()
207             .path(path)
208             .request(MediaType.APPLICATION_JSON)
209             .header("USER_ID", USER_ID)
210             .post(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
211
212         assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
213     }
214
215     @Test
216     void testPutPolicySuccess() {
217         String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
218         PolicyDefinition policy = new PolicyDefinition();
219         policy.setUniqueId(POLICY_ID);
220         PolicyDefinition successResponse = policy;
221         when(businessLogic
222             .updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID),
223                 eq(true))).thenReturn(successResponse);
224         Response response = target()
225             .path(path)
226             .request(MediaType.APPLICATION_JSON)
227             .header("USER_ID", USER_ID)
228             .put(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
229
230         assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
231     }
232
233     @Test
234     void testPutPolicyFailure() {
235         String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
236         PolicyDefinition policy = new PolicyDefinition();
237         Response response = target()
238             .path(path)
239             .request(MediaType.APPLICATION_JSON)
240             .header("USER_ID", USER_ID)
241             .put(Entity.entity(policy, MediaType.APPLICATION_JSON), Response.class);
242
243         assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
244     }
245
246     @Test
247     void testDeletePolicySuccess() {
248         String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
249         PolicyDefinition successResponse = new PolicyDefinition();
250         when(businessLogic
251             .deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true)))
252             .thenReturn(successResponse);
253         Response response = target()
254             .path(path)
255             .request(MediaType.APPLICATION_JSON)
256             .header("USER_ID", USER_ID)
257             .delete(Response.class);
258
259         assertEquals(response.getStatus(), HttpStatus.OK_200.getStatusCode());
260     }
261
262     @Test
263     void testDeletePolicyFailure() {
264         String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
265         Response response = target()
266             .path(path)
267             .request(MediaType.APPLICATION_JSON)
268             .header("USER_ID", USER_ID)
269             .delete(Response.class);
270
271         assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400.getStatusCode());
272     }
273
274     @Test
275     void getPolicyProperties_operationForbidden() {
276         // doThrow(new ComponentException(ActionStatus.GENERAL_ERROR)).when(businessLogic).getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID);
277         when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID))
278             .thenThrow(new ByActionStatusComponentException(ActionStatus.AUTH_FAILED, USER_ID));
279         Response response = buildGetPropertiesRequest().get();
280         assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode());
281     }
282
283     @Test//(expected = ComponentException.class)
284     void getPolicyProperties_unHandledError_returnGeneralError() {
285         when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID))
286             .thenThrow(new RuntimeException());
287         Response response = buildGetPropertiesRequest().get();
288         assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
289     }
290
291     @Test
292     void getPolicyProperties_wrongComponentType() {
293         Response response = buildGetPropertiesRequest("unknownType").get();
294         assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
295         //verifyZeroInteractions(businessLogic);
296     }
297
298     @Test
299     void getPolicyProperties() {
300         List<PropertyDataDefinition> properties = getPropertiesList();
301         when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID))
302             .thenReturn(properties);
303         List<PropertyDataDefinition> policyProps = buildGetPropertiesRequest()
304             .get(new GenericType<List<PropertyDataDefinition>>() {
305             });
306         assertThat(policyProps)
307             .usingElementComparatorOnFields("uniqueId")
308             .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
309     }
310
311     @Test
312     void updatePolicyPropertiesSuccess() {
313         List<PropertyDataDefinition> properties = getPropertiesList();
314         when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID),
315             any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(properties);
316         List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME,
317             properties).invoke(new GenericType<List<PropertyDataDefinition>>() {
318         });
319         assertThat(policyProps)
320             .usingElementComparatorOnFields("uniqueId")
321             .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
322     }
323
324     @Test
325     void updatePolicyTargetsSuccess() {
326         List<PolicyTargetDTO> targets = getTargetDTOList();
327         when(businessLogic
328             .updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(),
329                 eq(USER_ID))).thenReturn(new PolicyDefinition());
330         Response policyTargets = buildUpdateTargetsRequest(ComponentTypeEnum.RESOURCE_PARAM_NAME, targets).invoke();
331         assertThat(policyTargets.getStatus()).isEqualTo(200);
332     }
333
334     @Test
335     void updatePolicyPropertiesFailure() {
336         List<PropertyDataDefinition> properties = getPropertiesList();
337         ResponseFormat notFoundResponse = new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode());
338         when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID),
339             any(PropertyDataDefinition[].class), eq(USER_ID), eq(true)))
340             .thenThrow(new ByResponseFormatComponentException(notFoundResponse));
341         Response policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke();
342         assertEquals(HttpStatus.NOT_FOUND_404.getStatusCode(), policyProps.getStatus());
343     }
344
345     @Test
346     void testDeclarePropertyToPolicySuccess() {
347         Service service = new Service();
348         service.setUniqueId(SERVICE_ID);
349         service.addProperty(new PropertyDataDefinitionBuilder().setUniqueId(PROP_1).build());
350
351         PolicyDefinition policyDefinition = new PolicyDefinition();
352         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(SERVICE_ID, PROP_1));
353
354         setMocksForPropertyDeclaration(policyDefinition);
355
356         when(componentsUtils.getResponseFormat(eq(ActionStatus.OK)))
357             .thenReturn(new ResponseFormat(HttpStatus.OK_200.getStatusCode()));
358
359         Response declareResponse = buildDeclarePropertiesRequest(PROP_1).invoke();
360         assertEquals(HttpStatus.OK_200.getStatusCode(), declareResponse.getStatus());
361     }
362
363     @Test
364     void testUndeclarePolicySuccess() {
365         Service service = new Service();
366         service.setUniqueId(SERVICE_ID);
367         PropertyDefinition origProperty = new PropertyDataDefinitionBuilder().setUniqueId(PROP_1).build();
368
369         service.addProperty(origProperty);
370
371         PolicyDefinition policyDefinition = new PolicyDefinition();
372         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(SERVICE_ID, PROP_1));
373         service.addPolicy(policyDefinition);
374
375         addGetPolicyValueToProperty(origProperty, policyDefinition);
376
377         when(businessLogic
378             .deletePolicy(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(policyDefinition.getUniqueId()),
379                 eq(USER_ID), eq(true))).thenReturn(policyDefinition);
380
381         Response deleteResponse = buildDeletePolicyRequest(policyDefinition).invoke();
382         assertEquals(HttpStatus.OK_200.getStatusCode(), deleteResponse.getStatus());
383     }
384
385     private void addGetPolicyValueToProperty(PropertyDefinition propertyDefinition,
386                                              PolicyDefinition policyDefinition) {
387         JSONObject jobject = new JSONObject();
388         String origValue = Objects.isNull(propertyDefinition.getValue()) ? propertyDefinition.getDefaultValue()
389             : propertyDefinition.getValue();
390         jobject.put(GET_POLICY, null);
391         propertyDefinition.setValue(jobject.toJSONString());
392
393         GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition();
394         getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId());
395         getPolicyValueDataDefinition.setPropertyName(propertyDefinition.getName());
396
397         getPolicyValueDataDefinition.setOrigPropertyValue(origValue);
398
399         propertyDefinition.setGetPolicyValues(Collections.singletonList(getPolicyValueDataDefinition));
400     }
401
402     private void setMocksForPropertyDeclaration(PolicyDefinition policyDefinition) {
403         when(request.getSession()).thenReturn(session);
404         when(session.getServletContext()).thenReturn(context);
405         when(context.getAttribute(eq(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))).thenReturn(contextWrapper);
406         when(contextWrapper.getWebAppContext(any())).thenReturn(applicationContext);
407         when(applicationContext.getBean(eq(PolicyBusinessLogic.class))).thenReturn(businessLogic);
408         when(businessLogic.declareProperties(eq(USER_ID), eq(SERVICE_ID), any(), any())).thenReturn(
409             Either.left(Collections.singletonList(policyDefinition)));
410         when(componentsUtils
411             .convertJsonToObjectUsingObjectMapper(any(), any(), eq(ComponentInstInputsMap.class), eq(
412                 AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.SERVICE)))
413             .thenReturn(Either.left(getDeclarationBodyForProperty(PROP_1)));
414     }
415
416     private List<PropertyDataDefinition> getPropertiesList() {
417         PropertyDefinition prop1 = new PropertyDataDefinitionBuilder()
418             .setUniqueId("prop1")
419             .build();
420
421         PropertyDefinition prop2 = new PropertyDataDefinitionBuilder()
422             .setUniqueId("prop2")
423             .build();
424         return Arrays.asList(prop1, prop2);
425     }
426
427     private List<PolicyTargetDTO> getTargetDTOList() {
428         PolicyTargetDTO target1 = new PolicyTargetDTO();
429         target1.setUniqueIds(Collections.singletonList("uniqueId"));
430         target1.setType("GROUPS");
431
432         PolicyTargetDTO target2 = new PolicyTargetDTO();
433         target2.setUniqueIds(Collections.singletonList("uniqueId"));
434         target2.setType("component_Instances");
435
436         return Arrays.asList(target1, target2);
437     }
438
439     private Invocation.Builder buildGetPropertiesRequest(String componentType) {
440         return target(PROPS_URL)
441             .resolveTemplate("componentType", componentType)
442             .resolveTemplate("serviceId", SERVICE_ID)
443             .resolveTemplate("policyId", POLICY_ID)
444             .request(MediaType.APPLICATION_JSON)
445             .header(Constants.USER_ID_HEADER, USER_ID);
446
447     }
448
449     private Invocation buildUpdatePropertiesRequest(String componentType, List<PropertyDataDefinition> properties) {
450         return target(PROPS_URL)
451             .resolveTemplate("componentType", componentType)
452             .resolveTemplate("serviceId", SERVICE_ID)
453             .resolveTemplate("policyId", POLICY_ID)
454             .request(MediaType.APPLICATION_JSON)
455             .header(Constants.USER_ID_HEADER, USER_ID)
456             .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON));
457     }
458
459     private Invocation buildUpdateTargetsRequest(String componentType, List<PolicyTargetDTO> targets) {
460         return target(UPDATE_TARGETS_URL)
461             .resolveTemplate("componentType", componentType)
462             .resolveTemplate("componentId", COMPONENT_ID)
463             .resolveTemplate("policyId", POLICY_ID)
464             .request(MediaType.APPLICATION_JSON)
465             .header(Constants.USER_ID_HEADER, USER_ID)
466             .buildPost(Entity.entity(targets, MediaType.APPLICATION_JSON));
467     }
468
469     private Invocation.Builder buildGetPropertiesRequest() {
470         return target(PROPS_URL)
471             .resolveTemplate("componentType", "services")
472             .resolveTemplate("serviceId", SERVICE_ID)
473             .resolveTemplate("policyId", POLICY_ID)
474             .request(MediaType.APPLICATION_JSON)
475             .header(Constants.USER_ID_HEADER, USER_ID);
476     }
477
478     private Invocation buildDeletePolicyRequest(PolicyDefinition policyDefinition) {
479         return target(DELETE_URL)
480             .resolveTemplate("containerComponentType", "services")
481             .resolveTemplate("componentId", SERVICE_ID)
482             .resolveTemplate("policyId", policyDefinition.getUniqueId())
483             .request(MediaType.APPLICATION_JSON)
484             .header(Constants.USER_ID_HEADER, USER_ID)
485             .buildDelete();
486     }
487
488     private Invocation buildDeclarePropertiesRequest(String propertyId) {
489         return target(DECLARE_URL)
490             .resolveTemplate("componentType", "services")
491             .resolveTemplate("serviceId", SERVICE_ID)
492             .request(MediaType.APPLICATION_JSON)
493             .header(Constants.USER_ID_HEADER, USER_ID)
494             .buildPost(Entity.entity(getDeclarationBodyForProperty(propertyId), MediaType.APPLICATION_JSON));
495     }
496
497     private ComponentInstInputsMap getDeclarationBodyForProperty(String propertyId) {
498         ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
499         ComponentInstancePropInput propInput = new ComponentInstancePropInput();
500         PropertyDefinition propertyDefinition = new PropertyDefinition();
501
502         propertyDefinition.setType("string");
503         propertyDefinition.setUniqueId(SERVICE_ID + "." + propertyId);
504         propInput.setInput(propertyDefinition);
505         propInput.setPropertiesName(propertyId);
506
507         componentInstInputsMap.setComponentInstancePropertiesToPolicies(new HashMap<>());
508         componentInstInputsMap.getComponentInstancePropertiesToPolicies()
509             .put("componentInstancePropertiesToPolicies", Collections.singletonList(propInput));
510
511         return componentInstInputsMap;
512     }
513
514     @Override
515     protected ResourceConfig configure() {
516         forceSet(TestProperties.CONTAINER_PORT, "0");
517         return super.configure()
518             .register(new PolicyServlet(null, null, componentsUtils,
519                 servletUtils, null, businessLogic));
520     }
521
522     private static void createMocks() {
523         propertyDeclarationOrchestrator = Mockito.mock(PropertyDeclarationOrchestrator.class);
524         toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
525         businessLogic = Mockito.mock(PolicyBusinessLogic.class);
526         businessLogic.setPropertyDeclarationOrchestrator(propertyDeclarationOrchestrator);
527         businessLogic.setToscaOperationFacade(toscaOperationFacade);
528         BaseBusinessLogic bbl = new BaseBusinessLogicTest(Mockito.mock(IElementOperation.class),
529             Mockito.mock(IGroupOperation.class),
530             Mockito.mock(IGroupInstanceOperation.class), Mockito.mock(IGroupTypeOperation.class),
531             Mockito.mock(InterfaceOperation.class), Mockito.mock(InterfaceLifecycleOperation.class), Mockito.mock(
532             ArtifactsOperations.class));
533         PolicyServletTest.baseBusinessLogic = Mockito.spy(bbl);
534         PolicyServletTest.baseBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
535
536         componentsUtils = Mockito.mock(ComponentsUtils.class);
537         servletUtils = Mockito.mock(ServletUtils.class);
538         responseFormat = Mockito.mock(ResponseFormat.class);
539         roleAuthorizationHandler = Mockito.mock(RoleAuthorizationHandler.class);
540     }
541
542     private static class BaseBusinessLogicTest extends BaseBusinessLogic {
543
544         BaseBusinessLogicTest(IElementOperation elementDao,
545                               IGroupOperation groupOperation,
546                               IGroupInstanceOperation groupInstanceOperation,
547                               IGroupTypeOperation groupTypeOperation,
548                               InterfaceOperation interfaceOperation,
549                               InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
550                               ArtifactsOperations artifactToscaOperation) {
551             super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
552                 interfaceLifecycleTypeOperation, artifactToscaOperation);
553         }
554     }
555
556 }