Support Policies during Import Service
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / PolicyBusinessLogicTest.java
1 /*
2  * Copyright © 2016-2019 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.be.components.impl;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertNotNull;
22 import static org.junit.jupiter.api.Assertions.assertThrows;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24 import static org.junit.jupiter.api.Assertions.fail;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.ArgumentMatchers.anyBoolean;
27 import static org.mockito.ArgumentMatchers.anyMap;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.when;
30 import static org.openecomp.sdc.be.dao.api.ActionStatus.POLICY_TARGET_DOES_NOT_EXIST;
31 import static org.openecomp.sdc.be.dao.api.ActionStatus.PROPERTY_NOT_FOUND;
32
33 import fj.data.Either;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import org.apache.commons.collections.CollectionUtils;
41 import org.junit.jupiter.api.BeforeAll;
42 import org.junit.jupiter.api.BeforeEach;
43 import org.junit.jupiter.api.Test;
44 import org.junit.jupiter.api.extension.ExtendWith;
45 import org.mockito.InjectMocks;
46 import org.mockito.Mock;
47 import org.mockito.Mockito;
48 import org.mockito.MockitoAnnotations;
49 import org.mockito.junit.jupiter.MockitoExtension;
50 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
52 import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator;
53 import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
54 import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder;
55 import org.openecomp.sdc.be.components.utils.ResourceBuilder;
56 import org.openecomp.sdc.be.components.validation.UserValidations;
57 import org.openecomp.sdc.be.config.ConfigurationManager;
58 import org.openecomp.sdc.be.dao.api.ActionStatus;
59 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
60 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
61 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
62 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
66 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
67 import org.openecomp.sdc.be.impl.ComponentsUtils;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
70 import org.openecomp.sdc.be.model.ComponentInstance;
71 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
72 import org.openecomp.sdc.be.model.ComponentParametersView;
73 import org.openecomp.sdc.be.model.GroupDefinition;
74 import org.openecomp.sdc.be.model.LifecycleStateEnum;
75 import org.openecomp.sdc.be.model.PolicyDefinition;
76 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
77 import org.openecomp.sdc.be.model.PropertyDefinition;
78 import org.openecomp.sdc.be.model.Resource;
79 import org.openecomp.sdc.be.model.Service;
80 import org.openecomp.sdc.be.model.User;
81 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
84 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
85 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
86 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
87 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
88 import org.openecomp.sdc.common.impl.ExternalConfiguration;
89 import org.openecomp.sdc.common.impl.FSConfigurationSource;
90 import org.openecomp.sdc.exception.ResponseFormat;
91
92 @ExtendWith(MockitoExtension.class)
93 class PolicyBusinessLogicTest {
94
95     private static final String COMPONENT_ID = "componentId";
96     private static final String NON_EXIST_COMPONENT_ID = "nonExistComponentId";
97     private static final String COMPONENT_NAME = "componentName";
98     private static final String POLICY_TYPE_NAME = "policyTypeName";
99     private static final String POLICY_ID = "policyId";
100     private static final String INVALID_POLICY_ID = "invalidPolicyId";
101     private static final String POLICY_NAME = "policyName";
102     private static final String OTHER_POLICY_NAME = "otherPolicyName";
103     private static final String USER_ID = "jh0003";
104     private static final String UNIQUE_ID_EXSISTS = "uniqueIdExists";
105     private static final String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists";
106     private static final String CREATE_POLICY = "create Policy";
107     private static final String PROPERTY_NAME = "propDefinition";
108     private static final User user = buildUser();
109     private static final PolicyDefinition policy = buildPolicy(POLICY_NAME);
110     private static final Resource resource = buildResource();
111     private static final PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME);
112     private static final PolicyTypeDefinition policyType = buildPolicyType();
113     private static Either<Component, StorageOperationStatus> componentSuccessEither;
114     private static Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeSuccessEither;
115     private static Either<PolicyDefinition, StorageOperationStatus> policySuccessEither;
116     private final ConfigurationManager configurationManager = new ConfigurationManager(
117         new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
118     @Mock
119     private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
120     @InjectMocks
121     private PolicyBusinessLogic businessLogic;
122     @Mock
123     private ComponentsUtils componentsUtils;
124     @Mock
125     private ToscaOperationFacade toscaOperationFacade;
126     @Mock
127     private IGraphLockOperation graphLockOperation;
128     @Mock
129     private PolicyTypeOperation policyTypeOperation;
130     @Mock
131     private UserValidations userValidations;
132     @Mock
133     private JanusGraphDao janusGraphDao;
134     @Mock
135     private ApplicationDataTypeCache applicationDataTypeCache;
136     @Mock
137     private PropertyOperation propertyOperation;
138
139     @BeforeAll
140     static void setup() {
141         createResponses();
142     }
143
144     private static void createResponses() {
145         componentSuccessEither = Either.left(resource);
146         getPolicyTypeSuccessEither = Either.left(policyType);
147         policySuccessEither = Either.left(policy);
148     }
149
150     private static PolicyTypeDefinition buildPolicyType() {
151         PolicyTypeDefinition policyType = new PolicyTypeDefinition();
152         policyType.setType(POLICY_TYPE_NAME);
153         return policyType;
154     }
155
156     private static PolicyDefinition buildPolicy(String policyName) {
157         PolicyDefinition policy = new PolicyDefinition();
158         policy.setUniqueId(POLICY_ID);
159         policy.setPolicyTypeName(POLICY_TYPE_NAME);
160         policy.setComponentName(COMPONENT_NAME);
161         policy.setName(policyName);
162         return policy;
163     }
164
165     private static Resource buildResource() {
166         Resource resource = new Resource();
167         resource.setUniqueId(COMPONENT_ID);
168         resource.setName(COMPONENT_NAME);
169         resource.setCreatorUserId(USER_ID);
170         resource.setLastUpdaterUserId(USER_ID);
171         resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
172         resource.setIsDeleted(false);
173         resource.setResourceType(ResourceTypeEnum.VF);
174         resource.setToscaType(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
175         resource.setComponentType(ComponentTypeEnum.RESOURCE);
176         Map<String, PolicyDefinition> policies = new HashMap<>();
177         policies.put(POLICY_ID, policy);
178         resource.setPolicies(policies);
179         return resource;
180     }
181
182     private static Service buildService() {
183         Service service = new Service();
184         service.setUniqueId(COMPONENT_ID);
185         service.setName(COMPONENT_NAME);
186         service.setCreatorUserId(USER_ID);
187         service.setLastUpdaterUserId(USER_ID);
188         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
189         service.setIsDeleted(false);
190         service.setToscaType(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
191         service.setComponentType(ComponentTypeEnum.SERVICE);
192         Map<String, PolicyDefinition> policies = new HashMap<>();
193         policies.put(POLICY_ID, policy);
194         service.setPolicies(policies);
195         return service;
196     }
197
198     private static User buildUser() {
199         return new User(USER_ID);
200     }
201
202     @BeforeEach
203     void initBl() {
204         MockitoAnnotations.openMocks(this);
205         businessLogic.setComponentsUtils(componentsUtils);
206         businessLogic.setToscaOperationFacade(toscaOperationFacade);
207         businessLogic.setJanusGraphDao(janusGraphDao);
208         businessLogic.setUserValidations(userValidations);
209         businessLogic.setGraphLockOperation(graphLockOperation);
210         businessLogic.setPolicyTypeOperation(policyTypeOperation);
211         businessLogic.setApplicationDataTypeCache(applicationDataTypeCache);
212         businessLogic.setPropertyOperation(propertyOperation);
213         businessLogic.setPropertyDeclarationOrchestrator(propertyDeclarationOrchestrator);
214     }
215
216     @Test
217     void createPolicySuccessTest() {
218         stubValidateAndLockSuccess();
219         when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME), any())).thenReturn(getPolicyTypeSuccessEither);
220         when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither);
221         stubUnlockAndCommit();
222         PolicyDefinition response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
223         assertFalse(response.isEmpty());
224     }
225
226     @Test
227     void createPolicyOnResourceFromCsarDefinitionTest() {
228         String prop1 = "Prop_1";
229         String prop2 = "Prop_2";
230         Map<String, PolicyDefinition> policies = new HashMap<>();
231         PolicyDefinition policy = buildPolicy(POLICY_NAME);
232         Map<PolicyTargetType, List<String>> targets = getTargets();
233         PropertyDataDefinition[] properties = getProperties(prop1, prop2);
234         policy.setTargets(targets);
235         policy.setProperties(Arrays.asList(properties));
236         policies.put(POLICY_NAME, policy);
237
238         List<ComponentInstance> instanceList = new ArrayList<>();
239         ComponentInstance componentInstance = new ComponentInstance();
240         componentInstance.setUniqueId(UNIQUE_ID_EXSISTS);
241         componentInstance.setName(UNIQUE_ID_EXSISTS);
242         instanceList.add(componentInstance);
243
244         Resource newResource = buildResource();
245         newResource.setPolicies(policies);
246         newResource.setComponentInstances(instanceList);
247
248         when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME), any())).thenReturn(getPolicyTypeSuccessEither);
249         when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(Either.left(policy));
250         when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID)).thenReturn(Either.left(newResource));
251         when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), any(PromoteVersionEnum.class))).thenReturn(
252             Either.left(policy));
253         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1));
254         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2));
255
256         Map<String, PolicyDefinition> createdPolicy = businessLogic.createPolicies(newResource, policies);
257
258         assertFalse(createdPolicy.isEmpty());
259         PolicyDefinition newPolicy = createdPolicy.get(POLICY_NAME);
260         assertNotNull(newPolicy);
261         assertTrue(newPolicy.getIsFromCsar());
262         assertNotNull(newPolicy.getTargets());
263         assertNotNull(newPolicy.getProperties());
264         assertEquals(2, newPolicy.getProperties().size());
265         assertEquals(1, newPolicy.getTargets().size());
266     }
267
268     @Test
269     void createPolicyOnServiceFromCsarDefinitionTest() {
270         String prop1 = "Prop_1";
271         String prop2 = "Prop_2";
272         Map<String, PolicyDefinition> policies = new HashMap<>();
273         PolicyDefinition policy = buildPolicy(POLICY_NAME);
274         Map<PolicyTargetType, List<String>> targets = getTargets();
275         PropertyDataDefinition[] properties = getProperties(prop1, prop2);
276         policy.setTargets(targets);
277         policy.setProperties(Arrays.asList(properties));
278         policies.put(POLICY_NAME, policy);
279
280         List<ComponentInstance> instanceList = new ArrayList<>();
281         ComponentInstance componentInstance = new ComponentInstance();
282         componentInstance.setUniqueId(UNIQUE_ID_EXSISTS);
283         componentInstance.setName(UNIQUE_ID_EXSISTS);
284         instanceList.add(componentInstance);
285
286         Service newService = buildService();
287         newService.setPolicies(policies);
288         newService.setComponentInstances(instanceList);
289
290         when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME), any())).thenReturn(getPolicyTypeSuccessEither);
291         when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(Either.left(policy));
292         when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID)).thenReturn(Either.left(newService));
293         when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), any(PromoteVersionEnum.class))).thenReturn(
294             Either.left(policy));
295         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1));
296         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2));
297
298         Map<String, PolicyDefinition> createdPolicy = businessLogic.createPolicies(newService, policies);
299
300         assertFalse(createdPolicy.isEmpty());
301         PolicyDefinition newPolicy = createdPolicy.get(POLICY_NAME);
302         assertNotNull(newPolicy);
303         assertTrue(newPolicy.getIsFromCsar());
304         assertNotNull(newPolicy.getTargets());
305         assertNotNull(newPolicy.getProperties());
306         assertEquals(2, newPolicy.getProperties().size());
307         assertEquals(1, newPolicy.getTargets().size());
308         assertTrue(newPolicy.getTargets().containsKey(PolicyTargetType.COMPONENT_INSTANCES));
309         assertEquals(2, newPolicy.getTargets().get(PolicyTargetType.COMPONENT_INSTANCES).size());
310         newPolicy.getTargets().get(PolicyTargetType.COMPONENT_INSTANCES).forEach(t -> assertTrue(t.equals(UNIQUE_ID_EXSISTS)));
311         newPolicy.getProperties().forEach(p -> assertTrue(p.getName().equals(prop1) || p.getName().equals(prop2)));
312     }
313
314     @Test
315     void createPolicyUserFailureTest() {
316         ByActionStatusComponentException userNotFoundException = new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND);
317         when(userValidations.validateUserExists(USER_ID)).thenThrow(userNotFoundException);
318         try {
319             businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
320         } catch (ByActionStatusComponentException e) {
321             assertEquals(e.getActionStatus(), userNotFoundException.getActionStatus());
322         }
323     }
324
325     @Test
326     void createPolicyComponentFailureTest() {
327         when(userValidations.validateUserExists(USER_ID)).thenReturn(user);
328         Either<Component, StorageOperationStatus> componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND);
329         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenReturn(
330             ActionStatus.RESOURCE_NOT_FOUND);
331         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse);
332         assertThrows(ComponentException.class,
333             () -> businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true));
334     }
335
336     @Test
337     void createPolicyPolicyTypeFailureTest() {
338         stubValidateAndLockSuccess();
339         Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND);
340         when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME), any())).thenReturn(getPolicyTypeFailed);
341         when(componentsUtils.convertFromStorageResponse(getPolicyTypeFailed.right().value())).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
342         stubUnlockAndRollback();
343         assertThrows(ComponentException.class,
344             () -> businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true));
345     }
346
347     @Test
348     void createPolicyComponentTypeFailureTest() {
349         stubValidateAndLockSuccess();
350         when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME), any())).thenReturn(getPolicyTypeSuccessEither);
351         Either<PolicyDefinition, StorageOperationStatus> addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST);
352         when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes);
353         when(componentsUtils.convertFromStorageResponse(addPolicyRes.right().value())).thenReturn(ActionStatus.INVALID_CONTENT);
354
355         stubUnlockAndRollback();
356         assertThrows(ComponentException.class,
357             () -> businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true));
358     }
359
360     @Test
361     void updatePolicySuccessTest() {
362         stubValidateAndLockSuccess();
363         when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), any(PromoteVersionEnum.class))).thenReturn(
364             policySuccessEither);
365         stubUnlockAndCommit();
366         PolicyDefinition response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true);
367         assertFalse(response.isEmpty());
368     }
369
370     @Test
371     void updatePolicyNameFailureTest() {
372         stubValidateAndLockSuccess();
373         stubUnlockAndRollback();
374         assertThrows(ComponentException.class, () -> businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true));
375     }
376
377     @Test
378     void getPolicySuccessTest() {
379         stubValidationSuccess();
380         PolicyDefinition response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID);
381         assertFalse(response.isEmpty());
382     }
383
384     @Test
385     void getPolicyFailureTest() {
386         stubValidationSuccess();
387         assertThrows(ComponentException.class, () -> businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID));
388     }
389
390     @Test
391     void deletePolicySuccessTest() {
392         stubValidateAndLockSuccess();
393         stubCommit();
394         when(toscaOperationFacade.removePolicyFromComponent(COMPONENT_ID, POLICY_ID)).thenReturn(StorageOperationStatus.OK);
395         PolicyDefinition response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true);
396         assertFalse(response.isEmpty());
397     }
398
399     @Test
400     void deletePolicyFailureTest() {
401         stubValidateAndLockSuccess();
402         assertThrows(ComponentException.class,
403             () -> businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true));
404     }
405
406     @Test
407     void updatePolicyPropertiesSuccessTest() {
408         stubValidateAndLockSuccess();
409         String prop1 = "Name";
410         String prop2 = "Type";
411         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1));
412         when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2));
413         when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), any(PromoteVersionEnum.class))).thenReturn(
414             policySuccessEither);
415         stubUnlockAndCommit();
416         PropertyDataDefinition[] properties = getProperties(prop1, prop2);
417         policy.setProperties(Arrays.asList(properties));
418         List<PropertyDataDefinition> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties,
419             USER_ID, true);
420         List<PropertyDataDefinition> updatedProperties = response;
421         assertEquals(2, updatedProperties.size());
422     }
423
424     @Test
425     void updatePolicyTargetsSuccessTest() {
426         stubValidateAndLockSuccess();
427         stubGetToscaFullElementSuccess();
428         stubUpdatePolicyOfComponentSuccess();
429         stubGetToscaElementSuccess();
430         PolicyDefinition policyResult = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID);
431         Map<PolicyTargetType, List<String>> targets = getTargets();
432         assertTrue(policyResult.getTargets().values()
433             .containsAll(Arrays.asList(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES))));
434
435     }
436
437     @Test
438     void updatePolicyTargetsTargetIDFailureTest() {
439         stubValidateAndLockSuccess();
440         stubGetToscaFullElementSuccess();
441         stubGetToscaElementSuccess();
442         stubRollback();
443         Map<PolicyTargetType, List<String>> targetListFakeId = getTargetListFakeId();
444         final var componentException = assertThrows(ComponentException.class,
445             () -> businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, targetListFakeId, USER_ID));
446         assertNotNull(componentException);
447         assertEquals(POLICY_TARGET_DOES_NOT_EXIST, componentException.getActionStatus());
448         assertEquals(400, componentException.getResponseFormat().getStatus());
449         assertEquals(1, componentException.getParams().length);
450         assertEquals(UNIQUE_ID_DOESNT_EXSISTS, componentException.getParams()[0]);
451     }
452
453     @Test
454     void updatePolicyTargetsTypeFailureTest() {
455         stubValidateAndLockSuccess();
456         stubGetToscaFullElementSuccess();
457         stubGetToscaElementSuccess();
458         stubRollback();
459         Map<PolicyTargetType, List<String>> targetListFakeType = getTargetListFakeType();
460         final var componentException = assertThrows(ComponentException.class,
461             () -> businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, targetListFakeType, USER_ID));
462         assertNotNull(componentException);
463         assertEquals(POLICY_TARGET_DOES_NOT_EXIST, componentException.getActionStatus());
464         assertEquals(400, componentException.getResponseFormat().getStatus());
465         assertEquals(1, componentException.getParams().length);
466         assertEquals(UNIQUE_ID_EXSISTS, componentException.getParams()[0]);
467     }
468
469     private void stubUpdatePolicyOfComponentSuccess() {
470         when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy), any(PromoteVersionEnum.class))).thenReturn(
471             policySuccessEither);
472     }
473
474     @Test
475     void updatePolicyPropertiesFailureTest() {
476         stubValidateAndLockSuccess();
477         when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
478         policy.setProperties(null);
479         PropertyDataDefinition[] properties = getProperties("Name", "Type");
480         final var componentException = assertThrows(ComponentException.class,
481             () -> businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties, USER_ID, true));
482         assertNotNull(componentException);
483         assertEquals(PROPERTY_NOT_FOUND, componentException.getActionStatus());
484         assertEquals(404, componentException.getResponseFormat().getStatus());
485         assertEquals(0, componentException.getParams().length);
486     }
487
488     @Test
489     void testDeclarePropertiesAsPoliciesSuccess() {
490         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(resource));
491         when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK);
492         when(graphLockOperation.unlockComponent(any(), any())).thenReturn(StorageOperationStatus.OK);
493
494         when(propertyDeclarationOrchestrator.declarePropertiesToPolicies(any(), any())).thenReturn(Either.left(getDeclaredPolicies()));
495
496         Either<List<PolicyDefinition>, ResponseFormat> declaredPoliciesEither = businessLogic
497             .declareProperties(USER_ID,
498                 resource.getUniqueId(),
499                 ComponentTypeEnum.RESOURCE,
500                 getInputForPropertyToPolicyDeclaration());
501
502         assertTrue(declaredPoliciesEither.isLeft());
503
504         List<PolicyDefinition> declaredPolicies = declaredPoliciesEither.left().value();
505         assertTrue(CollectionUtils.isNotEmpty(declaredPolicies));
506         assertEquals(1, declaredPolicies.size());
507     }
508
509     @Test
510     void testDeclarePropertiesAsPoliciesFailure() {
511         when(toscaOperationFacade.getToscaElement(eq(NON_EXIST_COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(
512             Either.right(StorageOperationStatus.NOT_FOUND));
513         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenReturn(
514             ActionStatus.RESOURCE_NOT_FOUND);
515         try {
516             businessLogic
517                 .declareProperties(USER_ID,
518                     NON_EXIST_COMPONENT_ID,
519                     ComponentTypeEnum.RESOURCE,
520                     getInputForPropertyToPolicyDeclaration());
521         } catch (ComponentException e) {
522             assertEquals(ActionStatus.RESOURCE_NOT_FOUND, e.getActionStatus());
523             return;
524         }
525         fail();
526     }
527
528     private ComponentInstInputsMap getInputForPropertyToPolicyDeclaration() {
529         PropertyDefinition propertyDefinition = getPropertyDefinitionForDeclaration();
530
531         ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput();
532         componentInstancePropInput.setInput(propertyDefinition);
533         componentInstancePropInput.setPropertiesName(PROPERTY_NAME);
534
535         Map<String, List<ComponentInstancePropInput>> componentPropertiesToPolicies = new HashMap<>();
536         componentPropertiesToPolicies.put(resource.getUniqueId(), Collections.singletonList(componentInstancePropInput));
537
538         ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
539         componentInstInputsMap.setComponentInstancePropertiesToPolicies(componentPropertiesToPolicies);
540         return componentInstInputsMap;
541     }
542
543     private List<PolicyDefinition> getDeclaredPolicies() {
544         return Collections.singletonList(new PolicyDefinition(getPropertyDefinitionForDeclaration()));
545     }
546
547     private PropertyDefinition getPropertyDefinitionForDeclaration() {
548         PropertyDefinition propertyDefinition = new PropertyDefinition();
549         propertyDefinition.setUniqueId(PROPERTY_NAME);
550         propertyDefinition.setName(PROPERTY_NAME);
551         return propertyDefinition;
552     }
553
554     private PropertyDataDefinition[] getProperties(String prop1, String prop2) {
555         PropertyDataDefinition property1 = new PropertyDataDefinition();
556         property1.setName(prop1);
557         property1.setValue(prop1);
558         PropertyDataDefinition property2 = new PropertyDataDefinition();
559         property2.setName(prop2);
560         property2.setValue(prop2);
561         return new PropertyDataDefinition[]{property1, property2};
562     }
563
564     private void stubUnlockAndRollback() {
565         when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
566         stubRollback();
567     }
568
569     private void stubCommit() {
570         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
571     }
572
573     private void stubRollback() {
574         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
575     }
576
577     private void stubUnlockAndCommit() {
578         when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
579         stubCommit();
580     }
581
582     private void stubValidateAndLockSuccess() {
583         stubValidationSuccess();
584         when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
585     }
586
587     private void stubValidationSuccess() {
588         when(userValidations.validateUserExists(USER_ID)).thenReturn(user);
589         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither);
590     }
591
592     private void stubGetToscaFullElementSuccess() {
593         when(toscaOperationFacade.getToscaFullElement(COMPONENT_ID)).thenReturn(buildElementEither());
594     }
595
596     private void stubGetToscaElementSuccess() {
597         when(toscaOperationFacade.getToscaElement(COMPONENT_ID)).thenReturn(componentSuccessEither);
598     }
599
600     private Either<Component, StorageOperationStatus> buildElementEither() {
601         ResourceBuilder builder = new ResourceBuilder();
602         GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build();
603         ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder();
604         ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build();
605         return Either.left(builder.addGroup(groupDefinition).addComponentInstance(componentInstance).build());
606     }
607
608     private Map<PolicyTargetType, List<String>> getTargets() {
609         Map<PolicyTargetType, List<String>> targets = new HashMap<>();
610         targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS));
611         targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS));
612         return targets;
613     }
614
615     private Map<PolicyTargetType, List<String>> getTargetListFakeType() {
616         Map<PolicyTargetType, List<String>> targets = new HashMap<>();
617         targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS));
618         return targets;
619     }
620
621     private Map<PolicyTargetType, List<String>> getTargetListFakeId() {
622         Map<PolicyTargetType, List<String>> targets = new HashMap<>();
623         targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
624         targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
625         return targets;
626     }
627
628 }