f22b346052e3ea43f893e8714c1fa8ceacc1d793
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.components.impl;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.jupiter.api.Assertions.assertEquals;
25 import static org.junit.jupiter.api.Assertions.assertFalse;
26 import static org.junit.jupiter.api.Assertions.assertNotEquals;
27 import static org.junit.jupiter.api.Assertions.assertNotNull;
28 import static org.junit.jupiter.api.Assertions.assertNull;
29 import static org.junit.jupiter.api.Assertions.assertSame;
30 import static org.junit.jupiter.api.Assertions.assertThrows;
31 import static org.junit.jupiter.api.Assertions.assertTrue;
32 import static org.junit.jupiter.api.DynamicTest.dynamicTest;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anySet;
35 import static org.mockito.ArgumentMatchers.eq;
36 import static org.mockito.ArgumentMatchers.isNull;
37 import static org.mockito.Mockito.doReturn;
38 import static org.mockito.Mockito.doThrow;
39 import static org.mockito.Mockito.times;
40 import static org.mockito.Mockito.verify;
41 import static org.mockito.Mockito.when;
42 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE_PARAM_NAME;
43
44 import fj.data.Either;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collections;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Optional;
53 import java.util.Set;
54 import lombok.SneakyThrows;
55 import mockit.Deencapsulation;
56 import org.apache.commons.lang3.tuple.ImmutablePair;
57 import org.apache.commons.lang3.tuple.Pair;
58 import org.assertj.core.util.Lists;
59 import org.junit.jupiter.api.BeforeAll;
60 import org.junit.jupiter.api.BeforeEach;
61 import org.junit.jupiter.api.DynamicTest;
62 import org.junit.jupiter.api.Test;
63 import org.junit.jupiter.api.TestFactory;
64 import org.mockito.Mock;
65 import org.mockito.Mockito;
66 import org.mockito.MockitoAnnotations;
67 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
68 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
69 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
70 import org.openecomp.sdc.be.components.validation.UserValidations;
71 import org.openecomp.sdc.be.config.ConfigurationManager;
72 import org.openecomp.sdc.be.dao.api.ActionStatus;
73 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
74 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
75 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
76 import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;
77 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
78 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
79 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
80 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
81 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
82 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
83 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
84 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
85 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
86 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
87 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
88 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
89 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
90 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
91 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
92 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
93 import org.openecomp.sdc.be.exception.BusinessException;
94 import org.openecomp.sdc.be.impl.ComponentsUtils;
95 import org.openecomp.sdc.be.model.ArtifactDefinition;
96 import org.openecomp.sdc.be.model.CapabilityDefinition;
97 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
98 import org.openecomp.sdc.be.model.Component;
99 import org.openecomp.sdc.be.model.ComponentInstance;
100 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
101 import org.openecomp.sdc.be.model.ComponentInstanceInput;
102 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
103 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
104 import org.openecomp.sdc.be.model.ComponentParametersView;
105 import org.openecomp.sdc.be.model.DataTypeDefinition;
106 import org.openecomp.sdc.be.model.InputDefinition;
107 import org.openecomp.sdc.be.model.LifecycleStateEnum;
108 import org.openecomp.sdc.be.model.PolicyDefinition;
109 import org.openecomp.sdc.be.model.PropertyDefinition;
110 import org.openecomp.sdc.be.model.RelationshipImpl;
111 import org.openecomp.sdc.be.model.RelationshipInfo;
112 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
113 import org.openecomp.sdc.be.model.RequirementDefinition;
114 import org.openecomp.sdc.be.model.Resource;
115 import org.openecomp.sdc.be.model.Service;
116 import org.openecomp.sdc.be.model.User;
117 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
121 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
122 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
123 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
124 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
125 import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
126 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
127 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
128 import org.openecomp.sdc.common.api.ConfigurationSource;
129 import org.openecomp.sdc.common.impl.ExternalConfiguration;
130 import org.openecomp.sdc.common.impl.FSConfigurationSource;
131 import org.openecomp.sdc.common.util.ValidationUtils;
132 import org.openecomp.sdc.exception.ResponseFormat;
133
134 /**
135  * The test suite designed for test functionality of ComponentInstanceBusinessLogic class
136  */
137 class ComponentInstanceBusinessLogicTest {
138
139     private final static String USER_ID = "jh0003";
140     private final static String COMPONENT_ID = "componentId";
141     private final static String ORIGIN_COMPONENT_ID = "originComponentId";
142     private final static String ORIGIN_COMPONENT_VERSION = "1.0";
143     private final static String TO_INSTANCE_ID = "toInstanceId";
144     private final static String TO_INSTANCE_NAME = "toInstanceName";
145     private final static String COMPONENT_INSTANCE_ID = "componentInstanceId";
146     private final static String COMPONENT_INSTANCE_NAME = "componentInstanceName";
147     private final static String FROM_INSTANCE_ID = "fromInstanceId";
148     private final static String RELATION_ID = "relationId";
149     private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId";
150     private final static String CAPABILITY_UID = "capabilityUid";
151     private final static String CAPABILITY_NAME = "capabilityName";
152     private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId";
153     private final static String REQUIREMENT_UID = "requirementUid";
154     private final static String REQUIREMENT_NAME = "requirementName";
155     private final static String RELATIONSHIP_TYPE = "relationshipType";
156     private final static String ARTIFACT_1 = "cloudtech_k8s_charts.zip";
157     private final static String ARTIFACT_2 = "cloudtech_azure_day0.zip";
158     private final static String ARTIFACT_3 = "cloudtech_aws_configtemplate.zip";
159     private final static String ARTIFACT_4 = "k8s_charts.zip";
160     private final static String ARTIFACT_5 = "cloudtech_openstack_configtemplate.zip";
161     private final static String PROP_NAME = "propName";
162     private final static String NON_EXIST_NAME = "nonExistName";
163     private final static String INPUT_ID = "inputId";
164     private final static String ICON_NAME = "icon";
165
166     private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
167     @Mock
168     private ComponentInstancePropInput componentInstancePropInput;
169     @Mock
170     private ArtifactsBusinessLogic artifactsBusinessLogic;
171     @Mock
172     private ComponentsUtils componentsUtils;
173     @Mock
174     private ToscaOperationFacade toscaOperationFacade;
175     @Mock
176     private ForwardingPathOperation forwardingPathOperation;
177     @Mock
178     private User user;
179     @Mock
180     private UserValidations userValidations;
181     @Mock
182     private GraphLockOperation graphLockOperation;
183     @Mock
184     private JanusGraphDao janusGraphDao;
185     @Mock
186     private ApplicationDataTypeCache applicationDataTypeCache;
187     @Mock
188     private PropertyOperation propertyOperation;
189     @Mock
190     private ContainerInstanceTypesData containerInstanceTypeData;
191     @Mock
192     private CompositionBusinessLogic compositionBusinessLogic;
193     @Mock
194     private ToscaFunctionValidator toscaFunctionValidator;
195     @Mock
196     private PropertyBusinessLogic propertyBusinessLogic;
197     private Component service;
198     private Component resource;
199     private ComponentInstance toInstance;
200     private ComponentInstance fromInstance;
201     private RequirementCapabilityRelDef relation;
202     private List<ComponentInstanceProperty> ciPropertyList;
203     private List<ComponentInstanceInput> ciInputList;
204
205     @BeforeAll
206     static void beforeAll() {
207         initConfig();
208     }
209
210     private static void initConfig() {
211         final ConfigurationSource configurationSource = new FSConfigurationSource(
212             ExternalConfiguration.getChangeListener(),
213             "src/test/resources/config/catalog-be"
214         );
215         new ConfigurationManager(configurationSource);
216     }
217
218     @BeforeEach
219     void init() {
220         MockitoAnnotations.openMocks(this);
221         componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic(null, null, null, null, null, null, null, artifactsBusinessLogic, null,
222             null, forwardingPathOperation, null, null, toscaFunctionValidator, propertyBusinessLogic);
223         componentInstanceBusinessLogic.setComponentsUtils(componentsUtils);
224         componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
225         componentInstanceBusinessLogic.setUserValidations(userValidations);
226         componentInstanceBusinessLogic.setGraphLockOperation(graphLockOperation);
227         componentInstanceBusinessLogic.setJanusGraphDao(janusGraphDao);
228         componentInstanceBusinessLogic.setApplicationDataTypeCache(applicationDataTypeCache);
229         componentInstanceBusinessLogic.setPropertyOperation(propertyOperation);
230         componentInstanceBusinessLogic.setContainerInstanceTypesData(containerInstanceTypeData);
231         componentInstanceBusinessLogic.setCompositionBusinessLogic(compositionBusinessLogic);
232
233         stubMethods();
234         createComponents();
235     }
236
237     @Test
238     void testGetRelationByIdSuccess() {
239         getServiceRelationByIdSuccess(service);
240         getServiceRelationByIdSuccess(resource);
241     }
242
243     @Test
244     void testGetRelationByIdUserValidationFailure() {
245         getServiceRelationByIdUserValidationFailure(service);
246         getServiceRelationByIdUserValidationFailure(resource);
247     }
248
249     @Test
250     void testGetRelationByIdComponentNotFoundFailure() {
251         getRelationByIdComponentNotFoundFailure(service);
252         getRelationByIdComponentNotFoundFailure(resource);
253     }
254
255     @Test
256     void testForwardingPathOnVersionChange() {
257         getforwardingPathOnVersionChange();
258     }
259
260     @Test
261     void testIsCloudSpecificArtifact() {
262         assertThat(componentInstanceBusinessLogic.isCloudSpecificArtifact(ARTIFACT_1)).isTrue();
263         assertThat(componentInstanceBusinessLogic.isCloudSpecificArtifact(ARTIFACT_2)).isTrue();
264         assertThat(componentInstanceBusinessLogic.isCloudSpecificArtifact(ARTIFACT_3)).isTrue();
265         assertThat(componentInstanceBusinessLogic.isCloudSpecificArtifact(ARTIFACT_4)).isFalse();
266         assertThat(componentInstanceBusinessLogic.isCloudSpecificArtifact(ARTIFACT_5)).isFalse();
267     }
268
269     private void getforwardingPathOnVersionChange() {
270         String containerComponentParam = "services";
271         String containerComponentID = "121-cont";
272         String componentInstanceID = "121-cont-1-comp";
273         Service component = new Service();
274         Map<String, ForwardingPathDataDefinition> forwardingPaths = generateForwardingPath(componentInstanceID);
275
276         //Add existing componentInstance to component
277         List<ComponentInstance> componentInstanceList = new ArrayList<>();
278         ComponentInstance oldComponentInstance = new ComponentInstance();
279         oldComponentInstance.setName("OLD_COMP_INSTANCE");
280         oldComponentInstance.setUniqueId(componentInstanceID);
281         oldComponentInstance.setName(componentInstanceID);
282         oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID, "1-comp");
283         componentInstanceList.add(oldComponentInstance);
284         component.setComponentInstances(componentInstanceList);
285         component.setForwardingPaths(forwardingPaths);
286
287         List<ComponentInstance> componentInstanceListNew = new ArrayList<>();
288         ComponentInstance newComponentInstance = new ComponentInstance();
289         String new_Comp_UID = "2-comp";
290         newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID, new_Comp_UID);
291         newComponentInstance.setUniqueId(new_Comp_UID);
292         componentInstanceListNew.add(newComponentInstance);
293         Component component2 = new Service();
294         component2.setComponentInstances(componentInstanceListNew);
295
296         //Mock for getting component
297         when(toscaOperationFacade.getToscaElement(eq(containerComponentID), any(ComponentParametersView.class)))
298             .thenReturn(Either.left(component));
299         when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE));
300         when(toscaOperationFacade.getToscaFullElement(new_Comp_UID)).thenReturn(Either.left(component2));
301
302         Either<Set<String>, ResponseFormat> resultOp = componentInstanceBusinessLogic
303             .forwardingPathOnVersionChange(containerComponentParam,
304                 containerComponentID, componentInstanceID,
305                 newComponentInstance);
306         assertEquals(1, resultOp.left().value().size());
307         assertEquals("FP-ID-1", resultOp.left().value().iterator().next());
308
309     }
310
311     @SneakyThrows
312     @Test
313     void testCreateOrUpdatePropertiesValues2() {
314         String containerComponentID = "containerId";
315         String resourceInstanceId = "resourceId";
316         String componentInstanceID = "componentInstance";
317         List<ComponentInstanceProperty> properties = new ArrayList<>();
318         ComponentInstanceProperty property = new ComponentInstanceProperty();
319         property.setName("property");
320         property.setValue("newVal");
321         property.setType("string");
322         properties.add(property);
323
324         List<ComponentInstanceProperty> origProperties = new ArrayList<>();
325         ComponentInstanceProperty origProperty = new ComponentInstanceProperty();
326         origProperty.setName("property");
327         origProperty.setValue("value");
328         origProperty.setType("string");
329         origProperties.add(origProperty);
330
331         Map<String, DataTypeDefinition> types = new HashMap<>();
332         DataTypeDefinition dataTypeDef = new DataTypeDefinition();
333         types.put("string", dataTypeDef);
334
335         Component component = new Service();
336         component.setLastUpdaterUserId("userId");
337         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
338         Map<String, List<ComponentInstanceProperty>> componentInstanceProps = new HashMap<>();
339         componentInstanceProps.put("resourceId", origProperties);
340         component.setComponentInstancesProperties(componentInstanceProps);
341         ComponentInstance ci = createComponentInstance("ci1");
342         ci.setUniqueId("resourceId");
343         component.setComponentInstances(Arrays.asList(ci, createComponentInstance("ci2"),
344             createComponentInstance(componentInstanceID)));
345
346         when(toscaOperationFacade.getToscaElement(containerComponentID, JsonParseFlagEnum.ParseAll))
347             .thenReturn(Either.left(component));
348         when(graphLockOperation.lockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
349             .thenReturn(StorageOperationStatus.OK);
350         when(componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel())).thenReturn(types);
351         when(propertyOperation.validateAndUpdatePropertyValue(property.getType(), "newVal", true, null, types))
352             .thenReturn(Either.left("newVal"));
353         when(propertyOperation.validateAndUpdateRules("string", property.getRules(),
354             null, types, true)).thenReturn(ImmutablePair.of("string", null));
355         when(toscaOperationFacade.updateComponentInstanceProperty(component, ci.getUniqueId(),
356             origProperty)).thenReturn(StorageOperationStatus.OK);
357         origProperties.get(0).setValue("newVal");
358         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(component))
359             .thenReturn(Either.left(component));
360         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
361         when(graphLockOperation.unlockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
362             .thenReturn(StorageOperationStatus.OK);
363         when(propertyBusinessLogic.getComponentModelByComponentId(any())).thenReturn(component.getModel());
364         when(applicationDataTypeCache.getAll(any())).thenReturn(Either.left(types));
365         PropertyValueConstraintValidationUtil validationUtil = Mockito.mock(PropertyValueConstraintValidationUtil.class);
366         when(validationUtil.validatePropertyConstraints(any(),any(),any())).thenReturn(Either.left(any()));
367
368         Either<List<ComponentInstanceProperty>, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic
369             .createOrUpdatePropertiesValues(
370                 ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentID, resourceInstanceId, properties, "userId");
371         assertThat(responseFormatEither.left().value()).isEqualTo(properties);
372     }
373
374
375
376     @SneakyThrows
377     @Test
378     void testCreateOrUpdatePropertiesValuesPropertyNotExists() {
379         String containerComponentID = "containerId";
380         String resourceInstanceId = "resourceId";
381         String componentInstanceID = "componentInstance";
382         List<ComponentInstanceProperty> properties = new ArrayList<>();
383         ComponentInstanceProperty property = new ComponentInstanceProperty();
384         property.setName("property");
385         property.setValue("newVal");
386         property.setType("string");
387         properties.add(property);
388
389         List<ComponentInstanceProperty> origProperties = new ArrayList<>();
390
391         Component component = new Service();
392         component.setLastUpdaterUserId("userId");
393         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
394         Map<String, List<ComponentInstanceProperty>> componentInstanceProps = new HashMap<>();
395         componentInstanceProps.put("resourceId", origProperties);
396         component.setComponentInstancesProperties(componentInstanceProps);
397         ComponentInstance ci = createComponentInstance("ci1");
398         ci.setUniqueId("resourceId");
399         component.setComponentInstances(Arrays.asList(ci, createComponentInstance("ci2"),
400             createComponentInstance(componentInstanceID)));
401
402         when(toscaOperationFacade.getToscaElement(containerComponentID, JsonParseFlagEnum.ParseAll))
403             .thenReturn(Either.left(component));
404         when(graphLockOperation.lockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
405             .thenReturn(StorageOperationStatus.OK);
406         when(graphLockOperation.unlockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
407             .thenReturn(StorageOperationStatus.OK);
408         when(propertyBusinessLogic.getComponentModelByComponentId(any())).thenReturn(component.getModel());
409         Map<String, DataTypeDefinition> dataTypeMap = new HashMap<>();
410         when(applicationDataTypeCache.getAll(any())).thenReturn(Either.left(dataTypeMap));
411         PropertyValueConstraintValidationUtil validationUtil = Mockito.mock(PropertyValueConstraintValidationUtil.class);
412         when(validationUtil.validatePropertyConstraints(any(),any(),any()))
413             .thenReturn(Either.left(any()));
414
415         try {
416             componentInstanceBusinessLogic.createOrUpdatePropertiesValues(
417                 ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentID, resourceInstanceId, properties, "userId");
418         } catch (ComponentException e) {
419             assertThat(e.getActionStatus()).isEqualTo(ActionStatus.PROPERTY_NOT_FOUND);
420         }
421
422     }
423
424     @SneakyThrows
425     @Test
426     void testCreateOrUpdatePropertiesValuesValidationFailure() {
427         String containerComponentID = "containerId";
428         String resourceInstanceId = "resourceId";
429         String componentInstanceID = "componentInstance";
430         List<ComponentInstanceProperty> properties = new ArrayList<>();
431         ComponentInstanceProperty property = new ComponentInstanceProperty();
432         property.setName("property");
433         property.setValue("newVal");
434         property.setType("string");
435         properties.add(property);
436
437         List<ComponentInstanceProperty> origProperties = new ArrayList<>();
438         ComponentInstanceProperty origProperty = new ComponentInstanceProperty();
439         origProperty.setName("property");
440         origProperty.setValue("value");
441         origProperty.setType("string");
442         origProperties.add(origProperty);
443
444         Map<String, DataTypeDefinition> types = new HashMap<>();
445         DataTypeDefinition dataTypeDef = new DataTypeDefinition();
446         types.put("string", dataTypeDef);
447
448         Component component = new Service();
449         component.setLastUpdaterUserId("userId");
450         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
451         Map<String, List<ComponentInstanceProperty>> componentInstanceProps = new HashMap<>();
452         componentInstanceProps.put("resourceId", origProperties);
453         component.setComponentInstancesProperties(componentInstanceProps);
454         ComponentInstance ci = createComponentInstance("ci1");
455         ci.setUniqueId("resourceId");
456         component.setComponentInstances(Arrays.asList(ci, createComponentInstance("ci2"),
457             createComponentInstance(componentInstanceID)));
458
459         when(toscaOperationFacade.getToscaElement(containerComponentID, JsonParseFlagEnum.ParseAll))
460             .thenReturn(Either.left(component));
461         when(graphLockOperation.lockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
462             .thenReturn(StorageOperationStatus.OK);
463         when(componentsUtils.getAllDataTypes(applicationDataTypeCache, component.getModel())).thenReturn(types);
464         when(propertyOperation.validateAndUpdatePropertyValue(property.getType(), "newVal", true, null, types))
465             .thenReturn(Either.right(false));
466         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.BAD_REQUEST))
467             .thenReturn(ActionStatus.INVALID_CONTENT);
468         when(propertyBusinessLogic.getComponentModelByComponentId(any())).thenReturn(component.getModel());
469         Map<String, DataTypeDefinition> dataTypeMap = new HashMap<>();
470         when(applicationDataTypeCache.getAll(any())).thenReturn(Either.left(dataTypeMap));
471         PropertyValueConstraintValidationUtil validationUtil = Mockito.mock(PropertyValueConstraintValidationUtil.class);
472         when(validationUtil.validatePropertyConstraints(any(),any(),any()))
473             .thenReturn(Either.left(any()));
474
475         final Either<List<ComponentInstanceProperty>, ResponseFormat> response = componentInstanceBusinessLogic.createOrUpdatePropertiesValues(
476             ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentID, resourceInstanceId, properties, "userId");
477         assertThat(response.isRight()).as("Response should be an error").isTrue();
478         final ResponseFormat responseFormat = response.right().value();
479         assertThat(responseFormat.getStatus()).as("Response status should be as expected").isEqualTo(400);
480         assertThat(responseFormat.getMessageId()).as("Error message id should be as expected").isEqualTo("SVC4726");
481     }
482
483     @SneakyThrows
484     @Test
485     void testCreateOrUpdatePropertiesValuesMissingFieldFailure() {
486         String containerComponentID = "containerId";
487         String resourceInstanceId = "resourceId";
488         String componentInstanceID = "componentInstance";
489         List<ComponentInstanceProperty> properties = new ArrayList<>();
490         ComponentInstanceProperty property = new ComponentInstanceProperty();
491         property.setValue("newVal");
492         property.setType("string");
493         properties.add(property);
494
495         List<ComponentInstanceProperty> origProperties = new ArrayList<>();
496         ComponentInstanceProperty origProperty = new ComponentInstanceProperty();
497         origProperty.setName("property");
498         origProperty.setValue("value");
499         origProperty.setType("string");
500         origProperties.add(origProperty);
501
502         Component component = new Service();
503         component.setLastUpdaterUserId("userId");
504         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
505         Map<String, List<ComponentInstanceProperty>> componentInstanceProps = new HashMap<>();
506         componentInstanceProps.put("resourceId", origProperties);
507         component.setComponentInstancesProperties(componentInstanceProps);
508         ComponentInstance ci = createComponentInstance("ci1");
509         ci.setUniqueId("resourceId");
510         component.setComponentInstances(Arrays.asList(ci, createComponentInstance("ci2"),
511             createComponentInstance(componentInstanceID)));
512
513         when(toscaOperationFacade.getToscaElement(containerComponentID, JsonParseFlagEnum.ParseAll))
514             .thenReturn(Either.left(component));
515         when(graphLockOperation.lockComponent(containerComponentID, NodeTypeEnum.ResourceInstance))
516             .thenReturn(StorageOperationStatus.OK);
517         when(propertyBusinessLogic.getComponentModelByComponentId(any())).thenReturn(component.getModel());
518         Map<String, DataTypeDefinition> dataTypeMap = new HashMap<>();
519         when(applicationDataTypeCache.getAll(any())).thenReturn(Either.left(dataTypeMap));
520         PropertyValueConstraintValidationUtil validationUtil = Mockito.mock(PropertyValueConstraintValidationUtil.class);
521         when(validationUtil.validatePropertyConstraints(any(),any(),any()))
522             .thenReturn(Either.left(any()));
523
524         try {
525             componentInstanceBusinessLogic.createOrUpdatePropertiesValues(
526                 ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentID, resourceInstanceId, properties, "userId");
527         } catch (ComponentException e) {
528             assertThat(e.getActionStatus()).isEqualTo(ActionStatus.MISSING_PROPERTY_NAME);
529         }
530     }
531
532     @Test
533     void testDeleteForwardingPathsWhenComponentinstanceDeleted() {
534
535         ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services");
536         String containerComponentID = "Service-comp";
537         String componentInstanceID = "NodeA1";
538         Service component = new Service();
539         component
540             .setComponentInstances(Arrays.asList(createComponentInstance("NodeA2"), createComponentInstance("NodeB2"),
541                 createComponentInstance(componentInstanceID)));
542
543         component.addForwardingPath(createPath("path1", componentInstanceID, "NodeB1", "1"));
544         component.addForwardingPath(createPath("Path2", "NodeA2", "NodeB2", "2"));
545         when(toscaOperationFacade.getToscaElement(eq(containerComponentID), any(ComponentParametersView.class)))
546             .thenReturn(Either.left(component));
547         when(toscaOperationFacade.getToscaElement(containerComponentID)).thenReturn(Either.left(component));
548         when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet()))
549             .thenReturn(Either.left(new HashSet<>()));
550         final ComponentInstance ci = new ComponentInstance();
551         ci.setName(componentInstanceID);
552         ComponentInstance responseFormatEither = componentInstanceBusinessLogic
553             .deleteForwardingPathsRelatedTobeDeletedComponentInstance(
554                 containerComponentID, containerComponentType, ci);
555         assertFalse(responseFormatEither.isEmpty());
556     }
557
558     @Test
559     void testAddComponentInstanceDeploymentArtifacts() {
560
561         Component containerComponent = new Service();
562         ComponentInstance componentInstance = new ComponentInstance();
563         componentInstance.setUniqueId(COMPONENT_INSTANCE_ID);
564         Component originComponent = fillOriginComponent(new Resource());
565
566         Map<String, ArtifactDefinition> artifacts = new HashMap<>();
567         ArtifactDefinition deploymentArtifact1 = getArtifact("deploymentArtifact1", ArtifactTypeEnum.HEAT.getType());
568         artifacts.put(deploymentArtifact1.getArtifactLabel(), deploymentArtifact1);
569         ArtifactDefinition deploymentArtifact2 = getArtifact("deploymentArtifact2",
570             ArtifactTypeEnum.HEAT_ENV.getType());
571         artifacts.put(deploymentArtifact2.getArtifactLabel(), deploymentArtifact2);
572         ArtifactDefinition deploymentArtifact3 = getArtifact("deploymentArtifact3",
573             ArtifactTypeEnum.HEAT_VOL.getType());
574         artifacts.put(deploymentArtifact3.getArtifactLabel(), deploymentArtifact3);
575         ArtifactDefinition heatEnvPlaceHolder = getArtifact("deploymentArtifact4", ArtifactTypeEnum.HEAT_ENV.getType());
576         ArtifactDefinition heatEnvPlaceHolder2 = getArtifact("deploymentArtifact5",
577             ArtifactTypeEnum.HEAT_ENV.getType());
578
579         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = Either
580             .left(artifacts);
581
582         Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
583         finalDeploymentArtifacts.put(deploymentArtifact1.getArtifactLabel(), deploymentArtifact1);
584         finalDeploymentArtifacts.put(deploymentArtifact3.getArtifactLabel(), deploymentArtifact3);
585         finalDeploymentArtifacts.put(heatEnvPlaceHolder.getArtifactLabel(), heatEnvPlaceHolder);
586         finalDeploymentArtifacts.put(heatEnvPlaceHolder2.getArtifactLabel(), heatEnvPlaceHolder2);
587         when(artifactsBusinessLogic.getArtifacts(componentInstance.getComponentUid(), NodeTypeEnum.Resource,
588             ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(getResourceDeploymentArtifacts);
589         when(artifactsBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
590             deploymentArtifact1, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
591             NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
592             null)).thenReturn(heatEnvPlaceHolder);
593         when(artifactsBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
594             deploymentArtifact3, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
595             NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
596             null)).thenReturn(heatEnvPlaceHolder2);
597
598         componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
599         when(toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance,
600             finalDeploymentArtifacts)).thenReturn(StorageOperationStatus.OK);
601         when(toscaOperationFacade
602             .addGroupInstancesToComponentInstance(containerComponent, componentInstance, new ArrayList<>(),
603                 new HashMap<>()))
604             .thenReturn(StorageOperationStatus.OK);
605         when(toscaOperationFacade
606             .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, null))
607             .thenReturn(StorageOperationStatus.OK);
608
609         ActionStatus status = componentInstanceBusinessLogic.addComponentInstanceArtifacts(containerComponent,
610             componentInstance, originComponent, user, null);
611
612         assertThat(status).isEqualTo(ActionStatus.OK);
613
614     }
615
616     private Component fillOriginComponent(Resource originComponent) {
617         originComponent.setUniqueId("resourceId");
618         originComponent.setUniqueId(ORIGIN_COMPONENT_ID);
619         originComponent.setComponentInstances(Lists.newArrayList(toInstance, fromInstance));
620         originComponent.setComponentType(ComponentTypeEnum.RESOURCE);
621         originComponent.setState(LifecycleStateEnum.CERTIFIED);
622         return originComponent;
623     }
624
625     private ArtifactDefinition getArtifact(String artifactLabel, String artifactType) {
626         ArtifactDefinition artifactDefinition = new ArtifactDefinition();
627         artifactDefinition.setArtifactLabel(artifactLabel);
628         artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
629         artifactDefinition.setEsId("esId" + artifactLabel);
630         artifactDefinition.setArtifactType(artifactType);
631         artifactDefinition.setArtifactName("artifactName");
632         return artifactDefinition;
633     }
634
635     private ComponentInstance createComponentInstance(String path1) {
636         ComponentInstance componentInstance = new ComponentInstance();
637         componentInstance.setName(path1);
638         return componentInstance;
639     }
640
641     private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode, String uniqueId) {
642         ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName);
643         forwardingPath.setProtocol("protocol");
644         forwardingPath.setDestinationPortNumber("port");
645         forwardingPath.setUniqueId(uniqueId);
646         ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition =
647             new ListDataDefinition<>();
648         forwardingPathElementListDataDefinition
649             .add(new ForwardingPathElementDataDefinition(fromNode, toNode, "nodeAcpType", "nodeBcpType",
650                 "nodeDcpName", "nodeBcpName"));
651         forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
652
653         return forwardingPath;
654     }
655
656     private Map<String, ForwardingPathDataDefinition> generateForwardingPath(String componentInstanceID) {
657         ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName");
658         String protocol = "protocol";
659         forwardingPath.setProtocol(protocol);
660         forwardingPath.setDestinationPortNumber("DestinationPortNumber");
661         forwardingPath.setUniqueId("FP-ID-1");
662         ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition =
663             new ListDataDefinition<>();
664         forwardingPathElementListDataDefinition
665             .add(new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY",
666                 "nodeBcpType", "nodeDcpName", "nodeBcpName"));
667         forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
668         Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>();
669         forwardingPaths.put("1122", forwardingPath);
670         return forwardingPaths;
671     }
672
673     private void getServiceRelationByIdSuccess(Component component) {
674         Either<Component, StorageOperationStatus> getComponentRes = Either.left(component);
675         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
676             .thenReturn(getComponentRes);
677         Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic
678             .getRelationById(COMPONENT_ID,
679                 RELATION_ID, USER_ID,
680                 component.getComponentType());
681         assertThat(response.isLeft()).isTrue();
682     }
683
684     private void getServiceRelationByIdUserValidationFailure(Component component) {
685         doThrow(new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND)).when(userValidations).validateUserExists(USER_ID);
686         try {
687             componentInstanceBusinessLogic
688                 .getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
689         } catch (ByActionStatusComponentException e) {
690             assertSame(ActionStatus.USER_NOT_FOUND, e.getActionStatus());
691         }
692     }
693
694     private void getRelationByIdComponentNotFoundFailure(Component component) {
695         Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND);
696         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
697             .thenReturn(getComponentRes);
698
699         Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic
700             .getRelationById(COMPONENT_ID,
701                 RELATION_ID, USER_ID,
702                 component.getComponentType());
703         assertThat(response.isRight()).isTrue();
704     }
705
706     private void stubMethods() {
707         Mockito.lenient().when(userValidations.validateUserExists(eq(USER_ID))).thenReturn(user);
708         Mockito.lenient().when(componentsUtils
709             .convertFromStorageResponse(eq(StorageOperationStatus.GENERAL_ERROR), any(ComponentTypeEnum.class)))
710             .thenReturn(ActionStatus.GENERAL_ERROR);
711     }
712
713     private void createComponents() {
714         createRelation();
715         createInstances();
716         createProperties();
717         createInputs();
718         createService();
719         resource = createResource();
720     }
721
722     private Resource createResource() {
723         final Resource resource = new Resource();
724         resource.setUniqueId(COMPONENT_ID);
725         resource.setComponentInstancesRelations(Lists.newArrayList(relation));
726         resource.setComponentInstances(Lists.newArrayList(toInstance, fromInstance));
727         resource.setCapabilities(toInstance.getCapabilities());
728         resource.setRequirements(fromInstance.getRequirements());
729         resource.setComponentType(ComponentTypeEnum.RESOURCE);
730         resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
731         return resource;
732     }
733
734     private void createService() {
735         service = new Service();
736         service.setUniqueId(COMPONENT_ID);
737         service.setComponentInstancesRelations(Lists.newArrayList(relation));
738         service.setComponentInstances(Lists.newArrayList(toInstance, fromInstance));
739         service.setCapabilities(toInstance.getCapabilities());
740         service.setRequirements(fromInstance.getRequirements());
741         service.setComponentType(ComponentTypeEnum.SERVICE);
742         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
743         service.setLastUpdaterUserId(USER_ID);
744
745         Map<String, List<ComponentInstanceProperty>> ciPropertyMap = new HashMap<>();
746         ciPropertyMap.put(TO_INSTANCE_ID, ciPropertyList);
747         service.setComponentInstancesProperties(ciPropertyMap);
748
749         Map<String, List<ComponentInstanceInput>> ciInputMap = new HashMap<>();
750         ciInputMap.put(TO_INSTANCE_ID, ciInputList);
751         service.setComponentInstancesInputs(ciInputMap);
752     }
753
754     private void createInstances() {
755         toInstance = new ComponentInstance();
756         toInstance.setUniqueId(TO_INSTANCE_ID);
757         toInstance.setName(TO_INSTANCE_NAME);
758
759         fromInstance = new ComponentInstance();
760         fromInstance.setUniqueId(FROM_INSTANCE_ID);
761
762         CapabilityDataDefinition capability = new CapabilityDataDefinition();
763         capability.setOwnerId(CAPABILITY_OWNER_ID);
764         capability.setUniqueId(CAPABILITY_UID);
765         capability.setName(CAPABILITY_NAME);
766
767         Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
768         final CapabilityDefinition capabilityDefinition = new CapabilityDefinition(capability);
769         final ArrayList<ComponentInstanceProperty> properties = new ArrayList<>();
770         properties.add(componentInstancePropInput);
771         capabilityDefinition.setProperties(properties);
772         capabilities.put(capability.getName(), Lists.newArrayList(capabilityDefinition));
773
774         RequirementDataDefinition requirement = new RequirementDataDefinition();
775         requirement.setOwnerId(REQUIREMENT_OWNER_ID);
776         requirement.setUniqueId(REQUIREMENT_UID);
777         requirement.setName(REQUIREMENT_NAME);
778         requirement.setRelationship(RELATIONSHIP_TYPE);
779
780         Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
781         requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement)));
782
783         toInstance.setCapabilities(capabilities);
784         fromInstance.setRequirements(requirements);
785
786     }
787
788     private void createRelation() {
789
790         relation = new RequirementCapabilityRelDef();
791         CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
792         RelationshipInfo relationInfo = new RelationshipInfo();
793         relationInfo.setId(RELATION_ID);
794         relationship.setRelation(relationInfo);
795
796         relation.setRelationships(Lists.newArrayList(relationship));
797         relation.setToNode(TO_INSTANCE_ID);
798         relation.setFromNode(FROM_INSTANCE_ID);
799
800         relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID);
801         relationInfo.setCapabilityUid(CAPABILITY_UID);
802         relationInfo.setCapability(CAPABILITY_NAME);
803         relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID);
804         relationInfo.setRequirementUid(REQUIREMENT_UID);
805         relationInfo.setRequirement(REQUIREMENT_NAME);
806         RelationshipImpl relationshipImpl = new RelationshipImpl();
807         relationshipImpl.setType(RELATIONSHIP_TYPE);
808         relationInfo.setRelationships(relationshipImpl);
809     }
810
811     private void createProperties() {
812         // Create GetInputValueData
813         GetInputValueDataDefinition inputValueDef = new GetInputValueDataDefinition();
814         inputValueDef.setInputId(INPUT_ID);
815         List<GetInputValueDataDefinition> inputValueDefList = new ArrayList<>();
816         inputValueDefList.add(inputValueDef);
817         // Create ComponentInstanceProperty
818         ComponentInstanceProperty ciProperty = new ComponentInstanceProperty();
819         ciProperty.setGetInputValues(inputValueDefList);
820         ciProperty.setName(PROP_NAME);
821         // Create ComponentInstanceProperty list
822         ciPropertyList = new ArrayList<>();
823         ciPropertyList.add(ciProperty);
824     }
825
826     private void createInputs() {
827         // Create GetInputValueData
828         GetInputValueDataDefinition inputValueDef = new GetInputValueDataDefinition();
829         inputValueDef.setInputId(INPUT_ID);
830         List<GetInputValueDataDefinition> inputValueDefList = new ArrayList<>();
831         inputValueDefList.add(inputValueDef);
832         // Create ComponentInstanceInput
833         ComponentInstanceInput ciInput = new ComponentInstanceInput();
834         ciInput.setUniqueId(INPUT_ID);
835         ciInput.setName(PROP_NAME);
836         ciInput.setGetInputValues(inputValueDefList);
837         // Create ComponentInstanceInput list
838         ciInputList = new ArrayList<>();
839         ciInputList.add(ciInput);
840     }
841
842     private ComponentInstanceBusinessLogic createTestSubject() {
843         return componentInstanceBusinessLogic;
844     }
845
846     @Test
847     void testChangeServiceProxyVersion() {
848         ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
849
850         Either<ComponentInstance, ResponseFormat> result;
851
852         // default test
853         componentInstanceBusinessLogic = createTestSubject();
854         result = componentInstanceBusinessLogic.changeServiceProxyVersion();
855         assertNotNull(result);
856     }
857
858     @Test
859     void testCreateServiceProxy() {
860         ComponentInstanceBusinessLogic testSubject;
861         Either<ComponentInstance, ResponseFormat> result;
862
863         // default test
864         testSubject = createTestSubject();
865         result = testSubject.createServiceProxy();
866         assertNotNull(result);
867     }
868
869     @Test
870     void testDeleteServiceProxy() {
871         ComponentInstanceBusinessLogic testSubject;
872
873         Either<ComponentInstance, ResponseFormat> result;
874
875         // default test
876         testSubject = createTestSubject();
877         result = testSubject.deleteServiceProxy();
878         assertNotNull(result);
879     }
880
881     @Test
882     void testGetComponentInstanceInputsByInputIdEmpty() {
883         Component component = new Service();
884         String inputId = "";
885         List<ComponentInstanceInput> result;
886
887         result = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId);
888         assertNotNull(result);
889         assertThat(result.isEmpty()).isTrue();
890     }
891
892     @Test
893     void testGetComponentInstanceInputsByInputIdPresent() {
894         List<ComponentInstanceInput> result;
895
896         result = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(service, INPUT_ID);
897         assertNotNull(result);
898         assertThat(result.isEmpty()).isFalse();
899         assertThat(result.size()).isOne();
900         ComponentInstanceInput resultInput = result.get(0);
901         assertThat(resultInput.getComponentInstanceId()).isEqualTo(TO_INSTANCE_ID);
902         assertThat(resultInput.getComponentInstanceName()).isEqualTo(TO_INSTANCE_NAME);
903     }
904
905     @Test
906     void testGetComponentInstancePropertiesByInputIdEmpty() {
907         Component component = new Service();
908         String inputId = "";
909         List<ComponentInstanceProperty> result;
910
911         result = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId);
912         assertNotNull(result);
913         assertThat(result.isEmpty()).isTrue();
914     }
915
916     @Test
917     void testGetComponentInstancePropertiesByInputIdPresent() {
918         List<ComponentInstanceProperty> result;
919
920         result = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(service, INPUT_ID);
921         assertNotNull(result);
922         assertThat(result.size()).isOne();
923         ComponentInstanceProperty resultProperty = result.get(0);
924         assertThat(resultProperty.getComponentInstanceId()).isEqualTo(TO_INSTANCE_ID);
925         assertThat(resultProperty.getComponentInstanceName()).isEqualTo(TO_INSTANCE_NAME);
926     }
927
928     @Test
929     void testGetRelationById() {
930         ComponentInstanceBusinessLogic testSubject;
931         String componentId = "";
932         String relationId = "";
933         String userId = user.getUserId();
934         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE_INSTANCE;
935         Either<RequirementCapabilityRelDef, ResponseFormat> result;
936
937         // default test
938         testSubject = createTestSubject();
939         result = testSubject.getRelationById(componentId, relationId, userId, componentTypeEnum);
940         assertNotNull(result);
941     }
942
943     @Test
944     void testValidateParent() {
945         ComponentInstanceBusinessLogic testSubject;
946         resource = createResource();
947         String nodeTemplateId = "";
948         boolean result;
949
950         // default test
951         testSubject = createTestSubject();
952         result = Deencapsulation.invoke(testSubject, "validateParent", new Object[]{resource, nodeTemplateId});
953         assertFalse(result);
954     }
955
956     @Test
957     void testGetComponentType() {
958         ComponentInstanceBusinessLogic testSubject;
959         ComponentTypeEnum result;
960
961         // default test
962         testSubject = createTestSubject();
963         result = Deencapsulation.invoke(testSubject, "getComponentType", new Object[]{ComponentTypeEnum.class});
964         assertNotNull(result);
965     }
966
967     @Test
968     void testGetNewGroupName() {
969         ComponentInstanceBusinessLogic testSubject;
970         String oldPrefix = "";
971         String newNormailzedPrefix = "";
972         String qualifiedGroupInstanceName = "";
973         String result;
974
975         // test 1
976         testSubject = createTestSubject();
977         result = Deencapsulation.invoke(testSubject, "getNewGroupName",
978             new Object[]{oldPrefix, newNormailzedPrefix, qualifiedGroupInstanceName});
979         assertNotNull(result);
980     }
981
982     @Test
983     void testUpdateComponentInstanceMetadata_3() {
984         ComponentInstanceBusinessLogic testSubject;
985         createInstances();
986         ComponentInstance result;
987
988         // default test
989         testSubject = createTestSubject();
990         result = Deencapsulation
991             .invoke(testSubject, "updateComponentInstanceMetadata", new Object[]{toInstance, toInstance});
992         assertNotNull(result);
993     }
994
995     @Test
996     void testFindRelation() {
997         ComponentInstanceBusinessLogic testSubject;
998         String relationId = "";
999         List<RequirementCapabilityRelDef> requirementCapabilityRelations = new ArrayList<>();
1000         RequirementCapabilityRelDef result;
1001
1002         // default test
1003         testSubject = createTestSubject();
1004         result = Deencapsulation.invoke(testSubject, "findRelation",
1005             new Object[]{relationId, requirementCapabilityRelations});
1006         assertNull(result);
1007     }
1008
1009     @Test
1010     void testCreateOrUpdatePropertiesValues() {
1011         ComponentInstanceBusinessLogic testSubject;
1012         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1013         resource = createResource();
1014         String componentId = resource.getUniqueId();
1015         String resourceInstanceId = "";
1016         List<ComponentInstanceProperty> properties = new ArrayList<>();
1017         String userId = user.getUserId();
1018         Either<List<ComponentInstanceProperty>, ResponseFormat> result;
1019
1020         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll))
1021             .thenReturn(Either.left(resource));
1022
1023         // test 1
1024         testSubject = createTestSubject();
1025         result = testSubject
1026             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
1027                 userId);
1028         assertNotNull(result);
1029
1030         componentTypeEnum = null;
1031         result = testSubject
1032             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
1033                 userId);
1034         assertNotNull(result);
1035
1036         result = testSubject
1037             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
1038                 userId);
1039         assertNotNull(result);
1040     }
1041
1042     @Test
1043     void testUpdateCapabilityPropertyOnContainerComponent() {
1044         ComponentInstanceBusinessLogic testSubject;
1045         ComponentInstanceProperty property = new ComponentInstanceProperty();
1046         String newValue = "";
1047         resource = createResource();
1048         createInstances();
1049         String capabilityType = "";
1050         String capabilityName = "";
1051         ResponseFormat result;
1052
1053         // default test
1054         testSubject = createTestSubject();
1055         result = Deencapsulation.invoke(testSubject, "updateCapabilityPropertyOnContainerComponent",
1056             new Object[]{property, newValue, resource, toInstance, capabilityType, capabilityName});
1057         assertNull(result);
1058     }
1059
1060     @Test
1061     void testCreateOrUpdateInstanceInputValues() {
1062         ComponentInstanceBusinessLogic testSubject;
1063         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1064         resource = createResource();
1065         String componentId = resource.getUniqueId();
1066         String resourceInstanceId = "";
1067         List<ComponentInstanceInput> inputs = new ArrayList<>();
1068         String userId = user.getUserId();
1069         Either<List<ComponentInstanceInput>, ResponseFormat> result;
1070
1071         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll))
1072             .thenReturn(Either.left(resource));
1073
1074         // test 1
1075         testSubject = createTestSubject();
1076         result = testSubject
1077             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1078                 userId);
1079         assertNotNull(result);
1080         componentTypeEnum = null;
1081         result = testSubject
1082             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1083                 userId);
1084         assertNotNull(result);
1085
1086         result = testSubject
1087             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1088                 userId);
1089         assertNotNull(result);
1090     }
1091
1092     @Test
1093     void testCreateOrUpdateGroupInstancePropertyValue() {
1094         ComponentInstanceBusinessLogic testSubject;
1095         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1096         resource = createResource();
1097         String componentId = resource.getUniqueId();
1098         String resourceInstanceId = "";
1099         String groupInstanceId = "";
1100         ComponentInstanceProperty property = new ComponentInstanceProperty();
1101         String userId = user.getUserId();
1102         Either<ComponentInstanceProperty, ResponseFormat> result;
1103
1104         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata))
1105             .thenReturn(Either.left(resource));
1106
1107         // test 1
1108         testSubject = createTestSubject();
1109         result = testSubject
1110             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1111                 groupInstanceId, property, userId);
1112         assertNotNull(result);
1113         componentTypeEnum = null;
1114         result = testSubject
1115             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1116                 groupInstanceId, property, userId);
1117         assertNotNull(result);
1118
1119         result = testSubject
1120             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1121                 groupInstanceId, property, userId);
1122         assertNotNull(result);
1123     }
1124
1125     @Test
1126     void testDeletePropertyValue() {
1127         ComponentInstanceBusinessLogic testSubject;
1128         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1129         createService();
1130         String serviceId = service.getUniqueId();
1131         String resourceInstanceId = "";
1132         String propertyValueId = "";
1133         String userId = user.getUserId();
1134         Either<ComponentInstanceProperty, ResponseFormat> result;
1135
1136         when(toscaOperationFacade.getToscaElement(serviceId, JsonParseFlagEnum.ParseMetadata))
1137             .thenReturn(Either.left(service));
1138
1139         // test 1
1140         testSubject = createTestSubject();
1141         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1142             userId);
1143         assertNotNull(result);
1144         componentTypeEnum = null;
1145         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1146             userId);
1147         assertNotNull(result);
1148
1149         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1150             userId);
1151         assertNotNull(result);
1152     }
1153
1154     @Test
1155     void testGetComponentParametersViewForForwardingPath() {
1156         ComponentInstanceBusinessLogic testSubject;
1157         ComponentParametersView result;
1158
1159         // default test
1160         testSubject = createTestSubject();
1161         result = Deencapsulation.invoke(testSubject, "getComponentParametersViewForForwardingPath");
1162         assertNotNull(result);
1163     }
1164
1165     @Test
1166     void testGetResourceInstanceById() {
1167         ComponentInstanceBusinessLogic testSubject;
1168         resource = createResource();
1169         String instanceId = "";
1170         Either<ComponentInstance, StorageOperationStatus> result;
1171
1172         // default test
1173         testSubject = createTestSubject();
1174         result = Deencapsulation.invoke(testSubject, "getResourceInstanceById", new Object[]{resource, instanceId});
1175         assertNotNull(result);
1176     }
1177
1178     @Test
1179     void testUpdateInstanceCapabilityProperties_1() {
1180         ComponentInstanceBusinessLogic testSubject;
1181         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1182         resource = createResource();
1183         String containerComponentId = resource.getUniqueId();
1184         String componentInstanceUniqueId = "";
1185         String capabilityType = "";
1186         String capabilityName = "";
1187         List<ComponentInstanceProperty> properties = new ArrayList<>();
1188         String userId = user.getUserId();
1189         Either<List<ComponentInstanceProperty>, ResponseFormat> result;
1190
1191         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
1192             .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
1193         // test 1
1194         testSubject = createTestSubject();
1195         result = testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId,
1196             componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
1197         assertNotNull(result);
1198         when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.left(resource));
1199         result = testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId,
1200             componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
1201         assertNotNull(result);
1202     }
1203
1204     @Test
1205     void testUpdateInstanceRequirement() {
1206         ComponentInstanceBusinessLogic testSubject;
1207         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1208         createComponents();
1209         String userId = "userId";
1210         resource.setLastUpdaterUserId(userId);
1211         String containerComponentId = resource.getUniqueId();
1212         String componentInstanceUniqueId = TO_INSTANCE_ID;
1213         String capabilityType = "";
1214         String capabilityName = "";
1215         RequirementDefinition requirementDef = new RequirementDefinition();
1216
1217         Either<RequirementDefinition, ResponseFormat> result;
1218
1219         when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.left(resource));
1220         testSubject = createTestSubject();
1221         when(toscaOperationFacade.updateComponentInstanceRequirement(containerComponentId, TO_INSTANCE_ID, requirementDef)).thenReturn(StorageOperationStatus.OK);
1222         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(resource)).thenReturn(Either.left(resource));
1223         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource)))
1224             .thenReturn(StorageOperationStatus.OK);
1225         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource)))
1226             .thenReturn(StorageOperationStatus.OK);
1227
1228         result = testSubject.updateInstanceRequirement(componentTypeEnum, containerComponentId,
1229             componentInstanceUniqueId, requirementDef, userId);
1230         assertEquals(requirementDef, result.left().value());
1231
1232     }
1233
1234     @Test
1235     void testCopyComponentInstanceWrongUserId() {
1236
1237         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1238         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1239         String containerComponentId = service.getUniqueId();
1240         String componentInstanceId = resource.getUniqueId();
1241         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1242         service.setLastUpdaterUserId("wrong user id");
1243
1244         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1245         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1246         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1247             .thenReturn(leftServiceOp);
1248         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1249         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1250             .thenReturn(StorageOperationStatus.OK);
1251         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1252             .thenReturn(StorageOperationStatus.OK);
1253
1254         result = componentInstanceBusinessLogic
1255             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId,
1256                 USER_ID);
1257         assertNotNull(result);
1258
1259         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1260         assertThat(result.isRight()).isTrue();
1261     }
1262
1263     @Test
1264     void testCopyComponentInstanceComponentWrongState() {
1265         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1266         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1267         String containerComponentId = service.getUniqueId();
1268         String componentInstanceId = resource.getUniqueId();
1269         String oldServiceLastUpdatedUserId = service.getLastUpdaterUserId();
1270         service.setLastUpdaterUserId(USER_ID);
1271
1272         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1273         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1274         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1275             .thenReturn(leftServiceOp);
1276         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1277         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1278             .thenReturn(StorageOperationStatus.OK);
1279         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1280             .thenReturn(StorageOperationStatus.OK);
1281         result = componentInstanceBusinessLogic
1282             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId, USER_ID);
1283         assertNotNull(result);
1284         service.setLastUpdaterUserId(oldServiceLastUpdatedUserId);
1285         assertThat(result.isRight()).isTrue();
1286     }
1287
1288     @Test
1289     void testCopyComponentInstance() {
1290         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1291         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1292         String containerComponentId = service.getUniqueId();
1293         String componentInstanceId = resource.getUniqueId();
1294         String oldServiceLastUpdatedUserId = service.getLastUpdaterUserId();
1295         service.setLastUpdaterUserId(USER_ID);
1296         LifecycleStateEnum oldResourceLifeCycle = resource.getLifecycleState();
1297         resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1298
1299         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1300         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1301         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1302             .thenReturn(leftServiceOp);
1303         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1304             .thenReturn(StorageOperationStatus.OK);
1305         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1306             .thenReturn(StorageOperationStatus.OK);
1307
1308         result = componentInstanceBusinessLogic
1309             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId,
1310                 USER_ID);
1311         assertNotNull(result);
1312
1313         service.setLastUpdaterUserId(oldServiceLastUpdatedUserId);
1314         resource.setLifecycleState(oldResourceLifeCycle);
1315
1316         assertThat(result.isLeft()).isFalse();
1317     }
1318
1319     @Test
1320     void testCreateOrUpdateAttributeValueForCopyPaste() {
1321         ComponentInstance serviceComponentInstance = createComponetInstanceFromComponent(service);
1322         ComponentInstanceAttribute attribute = new ComponentInstanceAttribute();
1323         attribute.setType("string");
1324         attribute.setUniqueId("testCreateOrUpdateAttributeValueForCopyPaste");
1325         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1326         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1327         service.setLastUpdaterUserId(USER_ID);
1328         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1329
1330         Map<String, List<ComponentInstanceAttribute>> instAttrsMap = new HashMap<>();
1331         List<ComponentInstanceAttribute> instAttrsList = new ArrayList<>();
1332         ComponentInstanceAttribute prop = new ComponentInstanceAttribute();
1333         prop.setUniqueId(attribute.getUniqueId());
1334         instAttrsList.add(prop);
1335         instAttrsMap.put(toInstance.getUniqueId(), instAttrsList);
1336         service.setComponentInstancesAttributes(instAttrsMap);
1337
1338         Either<Component, StorageOperationStatus> serviceEitherLeft = Either.left(service);
1339         when(toscaOperationFacade.getToscaElement(serviceComponentInstance.getUniqueId(), JsonParseFlagEnum.ParseAll))
1340             .thenReturn(serviceEitherLeft);
1341         when(toscaOperationFacade.updateComponentInstanceAttribute(service, toInstance.getUniqueId(), attribute))
1342             .thenReturn(StorageOperationStatus.OK);
1343         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(service))
1344             .thenReturn(serviceEitherLeft);
1345
1346         Either<ComponentInstanceAttribute, ResponseFormat> result = Deencapsulation
1347             .invoke(componentInstanceBusinessLogic,
1348                 "createOrUpdateAttributeValueForCopyPaste",
1349                 ComponentTypeEnum.SERVICE,
1350                 serviceComponentInstance
1351                     .getUniqueId(),
1352                 toInstance.getUniqueId(), attribute,
1353                 USER_ID);
1354         assertNotNull(result);
1355
1356         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1357         service.setLifecycleState(oldLifeCycleState);
1358
1359         assertThat(result.isLeft()).isTrue();
1360         ComponentInstanceAttribute resultProp = result.left().value();
1361         assertEquals(1, resultProp.getPath().size());
1362         assertEquals(resultProp.getPath().get(0), toInstance.getUniqueId());
1363     }
1364
1365     @Test
1366     void testUpdateComponentInstanceProperty() {
1367
1368         String containerComponentId = service.getUniqueId();
1369         String componentInstanceId = "dummy_id";
1370         ComponentInstanceProperty property = Mockito.mock(ComponentInstanceProperty.class);
1371
1372         Either<Component, StorageOperationStatus> getComponent = Either.left(service);
1373         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(getComponent);
1374         StorageOperationStatus status = StorageOperationStatus.OK;
1375         when(toscaOperationFacade.updateComponentInstanceProperty(service, componentInstanceId, property))
1376             .thenReturn(status);
1377         Either<Component, StorageOperationStatus> updateContainerRes = Either.left(service);
1378         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(service))
1379             .thenReturn(updateContainerRes);
1380
1381         Either<String, ResponseFormat> result = Deencapsulation.invoke(componentInstanceBusinessLogic,
1382             "updateComponentInstanceProperty", containerComponentId, componentInstanceId, property);
1383         assertNotNull(result);
1384         assertThat(result.isLeft()).isTrue();
1385     }
1386
1387     @Test
1388     void testGetInputListDefaultValue() {
1389         Component component = service;
1390         String inputId = "dummy_id";
1391         String defaultValue = "dummy_default_value";
1392         List<InputDefinition> newInputs = new ArrayList<>();
1393         InputDefinition in = new InputDefinition();
1394         in.setUniqueId(inputId);
1395         in.setDefaultValue(defaultValue);
1396         newInputs.add(in);
1397         List<InputDefinition> oldInputs = service.getInputs();
1398         service.setInputs(newInputs);
1399
1400         Either<String, ResponseFormat> result =
1401             Deencapsulation.invoke(componentInstanceBusinessLogic, "getInputListDefaultValue", component, inputId);
1402
1403         service.setInputs(oldInputs);
1404
1405         assertEquals(result.left().value(), defaultValue);
1406     }
1407
1408     @Test
1409     void testBatchDeleteComponentInstanceFailureWrongType() {
1410         Map<String, List<String>> result;
1411         List<String> componentInstanceIdList = new ArrayList<>();
1412         String containerComponentParam = "WRONG_TYPE";
1413         String containerComponentId = "containerComponentId";
1414         String componentInstanceId = "componentInstanceId";
1415         componentInstanceIdList.add(componentInstanceId);
1416         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1417         List<String> deleteErrorIds = new ArrayList<>();
1418         deleteErrorIds.add(componentInstanceId);
1419         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1420         Either<Component, StorageOperationStatus> cont = Either.left(service);
1421         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, null))
1422             .thenReturn(ActionStatus.GENERAL_ERROR);
1423         when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class)))
1424             .thenReturn(cont);
1425
1426         try {
1427             result = componentInstanceBusinessLogic
1428                 .batchDeleteComponentInstance(containerComponentParam, containerComponentId, componentInstanceIdList,
1429                     USER_ID);
1430             assertNotNull(result);
1431             assertEquals(deleteErrorMap, result);
1432         } catch (ComponentException e) {
1433             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1434         }
1435     }
1436
1437     @Test
1438     void testBatchDeleteComponentInstanceFailureCompIds() {
1439         String containerComponentParam = ComponentTypeEnum.SERVICE_PARAM_NAME;
1440         String containerComponentId = "containerComponentId";
1441         String componentInstanceId = "componentInstanceId";
1442         List<String> componentInstanceIdList = new ArrayList<>();
1443         componentInstanceIdList.add(componentInstanceId);
1444         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1445         List<String> deleteErrorIds = new ArrayList<>();
1446         deleteErrorIds.add(componentInstanceId);
1447         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1448
1449         Either<Component, StorageOperationStatus> err = Either.right(StorageOperationStatus.GENERAL_ERROR);
1450         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1451             .thenReturn(err);
1452
1453         try {
1454             Map<String, List<String>> result = componentInstanceBusinessLogic.batchDeleteComponentInstance(
1455                 containerComponentParam, containerComponentId, componentInstanceIdList, USER_ID);
1456             assertNotNull(result);
1457             assertEquals(deleteErrorMap, result);
1458         } catch (ComponentException e) {
1459             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1460         }
1461     }
1462
1463     @Test
1464     void testBatchDeleteComponentInstanceSuccess() {
1465         Map<String, List<String>> result;
1466         String containerComponentParam = ComponentTypeEnum.SERVICE_PARAM_NAME;
1467         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1468         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1469         service.setLastUpdaterUserId(USER_ID);
1470         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1471         String containerComponentId = service.getUniqueId();
1472         String componentInstanceId = TO_INSTANCE_ID;
1473         List<String> componentInstanceIdList = new ArrayList<>();
1474         componentInstanceIdList.add(componentInstanceId);
1475         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1476         List<String> deleteErrorIds = new ArrayList<>();
1477         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1478
1479         Either<Component, StorageOperationStatus> cont = Either.left(service);
1480         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1481             .thenReturn(StorageOperationStatus.OK);
1482         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1483             .thenReturn(StorageOperationStatus.OK);
1484         ImmutablePair<Component, String> pair = new ImmutablePair<>(resource, TO_INSTANCE_ID);
1485         Either<ImmutablePair<Component, String>, StorageOperationStatus> result2 = Either.left(pair);
1486         when(toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(service, componentInstanceId))
1487             .thenReturn(result2);
1488         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1489             .thenReturn(cont);
1490         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
1491
1492         result = componentInstanceBusinessLogic
1493             .batchDeleteComponentInstance(containerComponentParam, containerComponentId,
1494                 componentInstanceIdList, USER_ID);
1495         assertNotNull(result);
1496
1497         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1498         service.setLifecycleState(oldLifeCycleState);
1499         assertEquals(deleteErrorMap, result);
1500     }
1501
1502     @Test
1503     void testDissociateRIFromRIFailDissociate() {
1504
1505         List<RequirementCapabilityRelDef> result;
1506         RequirementCapabilityRelDef ref = new RequirementCapabilityRelDef();
1507         ref.setFromNode(FROM_INSTANCE_ID);
1508         ref.setToNode(TO_INSTANCE_ID);
1509         List<CapabilityRequirementRelationship> relationships = new ArrayList<>();
1510         CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
1511         RelationshipInfo ri = new RelationshipInfo();
1512         ri.setRequirement(REQUIREMENT_NAME);
1513         relationship.setRelation(ri);
1514         relationships.add(relationship);
1515         ref.setRelationships(relationships);
1516         List<RequirementCapabilityRelDef> requirementDefList = new ArrayList<>();
1517         requirementDefList.add(ref);
1518         ComponentTypeEnum componentTypeEnum = service.getComponentType();
1519         String componentId = service.getUniqueId();
1520         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1521         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1522         service.setLastUpdaterUserId(USER_ID);
1523         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1524
1525         Either<Component, StorageOperationStatus> cont = Either.left(service);
1526         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1527             .thenReturn(cont);
1528         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1529             .thenReturn(StorageOperationStatus.OK);
1530         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1531             .thenReturn(StorageOperationStatus.OK);
1532         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultEither;
1533         resultEither = Either.right(StorageOperationStatus.OK);
1534         when(componentsUtils.convertFromStorageResponseForResourceInstance(StorageOperationStatus.OK, true))
1535             .thenReturn(ActionStatus.GENERAL_ERROR);
1536         when(toscaOperationFacade.dissociateResourceInstances(componentId, ref)).thenReturn(resultEither);
1537
1538         try {
1539             result = componentInstanceBusinessLogic
1540                 .batchDissociateRIFromRI(componentId, USER_ID, requirementDefList, componentTypeEnum);
1541             assertNotNull(result);
1542             assertEquals(new ArrayList<>(), result);
1543         } catch (ComponentException e) {
1544             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1545         }
1546
1547         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1548         service.setLifecycleState(oldLifeCycleState);
1549
1550     }
1551
1552     @Test
1553     void testDissociateRIFromRISuccess() {
1554
1555         List<RequirementCapabilityRelDef> result;
1556         RequirementCapabilityRelDef ref = new RequirementCapabilityRelDef();
1557         List<RequirementCapabilityRelDef> requirementDefList = new ArrayList<>();
1558         requirementDefList.add(ref);
1559         ComponentTypeEnum componentTypeEnum = service.getComponentType();
1560         String componentId = service.getUniqueId();
1561         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1562         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1563         service.setLastUpdaterUserId(USER_ID);
1564         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1565
1566         Either<Component, StorageOperationStatus> cont = Either.left(service);
1567         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1568             .thenReturn(cont);
1569         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1570             .thenReturn(StorageOperationStatus.OK);
1571         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1572             .thenReturn(StorageOperationStatus.OK);
1573         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultEither;
1574         resultEither = Either.left(ref);
1575         when(toscaOperationFacade.dissociateResourceInstances(componentId, ref)).thenReturn(resultEither);
1576
1577         result = componentInstanceBusinessLogic
1578             .batchDissociateRIFromRI(componentId, USER_ID, requirementDefList, componentTypeEnum);
1579         assertNotNull(result);
1580
1581         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1582         service.setLifecycleState(oldLifeCycleState);
1583
1584         assertEquals(requirementDefList, result);
1585     }
1586
1587     @Test
1588     void testGetComponentInstancePropertyByPolicyId_success() {
1589         Optional<ComponentInstanceProperty> propertyCandidate =
1590             getComponentInstanceProperty(PROP_NAME);
1591
1592         assertThat(propertyCandidate).isPresent();
1593         assertEquals(PROP_NAME, propertyCandidate.get().getName());
1594     }
1595
1596     @Test
1597     void testGetComponentInstancePropertyByPolicyId_failure() {
1598         Optional<ComponentInstanceProperty> propertyCandidate =
1599             getComponentInstanceProperty(NON_EXIST_NAME);
1600
1601         assertEquals(propertyCandidate, Optional.empty());
1602     }
1603
1604     private Optional<ComponentInstanceProperty> getComponentInstanceProperty(String propertyName) {
1605         ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
1606         componentInstanceProperty.setName(propertyName);
1607
1608         PolicyDefinition policyDefinition = getPolicyDefinition();
1609         componentInstanceProperty.setGetPolicyValues(policyDefinition.getGetPolicyValues());
1610
1611         service.setComponentInstancesProperties(
1612             Collections.singletonMap(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceProperty)));
1613
1614         return componentInstanceBusinessLogic.getComponentInstancePropertyByPolicyId(service, policyDefinition);
1615     }
1616
1617     private PolicyDefinition getPolicyDefinition() {
1618         PolicyDefinition policyDefinition = new PolicyDefinition();
1619         policyDefinition.setInstanceUniqueId(COMPONENT_INSTANCE_ID);
1620         policyDefinition.setName(PROP_NAME);
1621
1622         GetPolicyValueDataDefinition getPolicy = new GetPolicyValueDataDefinition();
1623         getPolicy.setPropertyName(PROP_NAME);
1624
1625         List<GetPolicyValueDataDefinition> getPolicies = new ArrayList<>();
1626         getPolicies.add(getPolicy);
1627         policyDefinition.setGetPolicyValues(getPolicies);
1628
1629         return policyDefinition;
1630     }
1631
1632     private ComponentInstance createComponetInstanceFromComponent(Component component) {
1633         ComponentInstance componentInst = new ComponentInstance();
1634         componentInst.setUniqueId(component.getUniqueId());
1635         componentInst.setComponentUid(component.getUniqueId() + "_test");
1636         componentInst.setPosX("10");
1637         componentInst.setPosY("10");
1638         componentInst.setCapabilities(component.getCapabilities());
1639         componentInst.setRequirements(component.getRequirements());
1640         componentInst.setArtifacts(component.getArtifacts());
1641         componentInst.setDeploymentArtifacts(component.getDeploymentArtifacts());
1642         return componentInst;
1643     }
1644
1645     // Prepare ComponentInstance & Resource objects used in createComponentInstance() tests
1646
1647     private Pair<ComponentInstance, Resource> prepareResourcesForCreateComponentInstanceTest() {
1648         ComponentInstance instanceToBeCreated = new ComponentInstance();
1649         instanceToBeCreated.setName(COMPONENT_INSTANCE_NAME);
1650         instanceToBeCreated.setUniqueId(COMPONENT_INSTANCE_ID);
1651         instanceToBeCreated.setComponentUid(ORIGIN_COMPONENT_ID);
1652         instanceToBeCreated.setOriginType(OriginTypeEnum.VF);
1653
1654         Resource originComponent = new Resource();
1655         originComponent.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1656         originComponent.setResourceType(ResourceTypeEnum.VF);
1657         originComponent.setVersion(ORIGIN_COMPONENT_VERSION);
1658         originComponent.setIcon(ICON_NAME);
1659
1660         return Pair.of(instanceToBeCreated, originComponent);
1661     }
1662     // Common part for testing component instance name validation
1663
1664     private void testCreateComponentInstanceNameValidationFailure(String ciName) {
1665         ComponentInstance ci = new ComponentInstance();
1666         ci.setName(ciName);
1667
1668         // Stub for getting component
1669         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1670             .thenReturn(Either.left(service));
1671
1672         // Expecting ByActionStatusComponentException
1673         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1674             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1675         });
1676         assertEquals(ActionStatus.INVALID_COMPONENT_NAME, e.getActionStatus());
1677     }
1678     @TestFactory
1679     Iterable<DynamicTest> testCreateComponentInstanceNameValidationFailureFactory() {
1680         String longName = String.join("", Collections.nCopies(ValidationUtils.COMPONENT_NAME_MAX_LENGTH + 1, "x"));
1681         String invalidName = "componentInstance#name";
1682         return Arrays.asList(
1683             dynamicTest("instance name is empty", () ->
1684                 testCreateComponentInstanceNameValidationFailure("")),
1685             dynamicTest("instance name is too long", () ->
1686                 testCreateComponentInstanceNameValidationFailure(longName)),
1687             dynamicTest("instance name includes invalid character", () ->
1688                 testCreateComponentInstanceNameValidationFailure(invalidName))
1689         );
1690     }
1691
1692     @Test
1693     void testCreateComponentInstanceFailToGetComponent() {
1694         ComponentInstance ci = prepareResourcesForCreateComponentInstanceTest().getLeft();
1695
1696         // Stub for getting component
1697         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1698             .thenReturn(Either.left(service));
1699         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1700             .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1701         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE))
1702             .thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
1703
1704         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1705             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1706         });
1707         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
1708     }
1709
1710     @Test
1711     void testCreateComponentInstanceFailureInvalidState() {
1712         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1713         ComponentInstance ci = p.getLeft();
1714         Resource originComponent = p.getRight();
1715         originComponent.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1716
1717         // Stub for getting component
1718         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1719             .thenReturn(Either.left(service));
1720         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1721             .thenReturn(Either.left(originComponent));
1722
1723         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1724             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1725         });
1726         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE);
1727     }
1728
1729     @Test
1730     void testCreateComponentInstanceFailureArchived() {
1731         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1732         ComponentInstance ci = p.getLeft();
1733         Resource originComponent = p.getRight();
1734         originComponent.setArchived(Boolean.TRUE);
1735
1736         // Stub for getting component
1737         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1738             .thenReturn(Either.left(service));
1739         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1740             .thenReturn(Either.left(originComponent));
1741
1742         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1743             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1744         });
1745         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.COMPONENT_IS_ARCHIVED);
1746     }
1747
1748     @Test
1749     void testCreateComponentInstanceFailureInvalidOriginType() {
1750         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1751         ComponentInstance ci = p.getLeft();
1752         Resource originComponent = p.getRight();
1753         ci.setOriginType(OriginTypeEnum.VFC); // Set different type from origin
1754
1755         // Stub for getting component
1756         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1757             .thenReturn(Either.left(service));
1758         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1759             .thenReturn(Either.left(originComponent));
1760
1761         final ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1762             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1763         });
1764         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.INVALID_CONTENT);
1765     }
1766
1767     @Test
1768     void testCreateComponentInstanceFailureCannotContainInstance() {
1769         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1770         final ComponentInstance ci = p.getLeft();
1771         final Resource originComponent = p.getRight();
1772
1773         // Stub for getting component
1774         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1775             .thenReturn(Either.left(service));
1776         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1777             .thenReturn(Either.left(originComponent));
1778         // Assume services cannot contain VF resource
1779         when(containerInstanceTypeData.isAllowedForServiceComponent(ResourceTypeEnum.VF, null))
1780             .thenReturn(false);
1781
1782         ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class, () -> {
1783             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1784         });
1785         assertThat(actualException.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE);
1786         verify(containerInstanceTypeData, times(1)).isAllowedForServiceComponent(ResourceTypeEnum.VF, null);
1787
1788         //given
1789         final Resource resource = createResource();
1790         resource.setResourceType(ResourceTypeEnum.VF);
1791         resource.setLastUpdaterUserId(USER_ID);
1792         //when
1793         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1794             .thenReturn(Either.left(resource));
1795         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1796             .thenReturn(Either.left(originComponent));
1797         when(containerInstanceTypeData.isAllowedForResourceComponent(ResourceTypeEnum.VF, ResourceTypeEnum.VF))
1798             .thenReturn(false);
1799         actualException = assertThrows(ByActionStatusComponentException.class, () -> {
1800             componentInstanceBusinessLogic.createComponentInstance(RESOURCE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1801         });
1802         //then
1803         assertThat(actualException.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE);
1804     }
1805
1806     @Test
1807     void testCreateComponentInstanceFailureAddToGraph() {
1808         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1809         final ComponentInstance ci = p.getLeft();
1810         final Resource originComponent = p.getRight();
1811
1812         // TODO Refactor createComponentInstance() method and reduce these mocks
1813         //      not to target the internal details too much
1814         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1815             .thenReturn(Either.left(service));
1816         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1817             .thenReturn(Either.left(originComponent));
1818         when(containerInstanceTypeData.isAllowedForServiceComponent(ResourceTypeEnum.VF, null))
1819             .thenReturn(true);
1820         Mockito.doNothing().when(compositionBusinessLogic).validateAndSetDefaultCoordinates(ci);
1821         when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1822             .thenReturn(StorageOperationStatus.OK);
1823         when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(service, originComponent, ci, false, user))
1824             .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
1825         when(componentsUtils.convertFromStorageResponseForResourceInstance(StorageOperationStatus.BAD_REQUEST, true))
1826             .thenReturn(ActionStatus.INVALID_CONTENT);
1827         when(componentsUtils.getResponseFormatForResourceInstance(ActionStatus.INVALID_CONTENT, "", null))
1828             .thenReturn(new ResponseFormat());
1829         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1830         when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1831             .thenReturn(StorageOperationStatus.OK);
1832
1833         assertThrows(ByResponseFormatComponentException.class, () -> {
1834             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1835         });
1836         verify(containerInstanceTypeData, times(1))
1837             .isAllowedForServiceComponent(ResourceTypeEnum.VF, null);
1838         verify(compositionBusinessLogic, times(1)).validateAndSetDefaultCoordinates(ci);
1839         verify(toscaOperationFacade, times(1))
1840             .addComponentInstanceToTopologyTemplate(service, originComponent, ci, false, user);
1841         verify(graphLockOperation, times(1)).unlockComponent(COMPONENT_ID, NodeTypeEnum.Service);
1842     }
1843
1844     @Test
1845     void testCreateComponentInstanceSuccess() {
1846         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1847         final ComponentInstance instanceToBeCreated = p.getLeft();
1848         final Resource originComponent = p.getRight();
1849
1850         final Service updatedService = new Service();
1851         updatedService.setComponentInstances(Collections.singletonList(instanceToBeCreated));
1852         updatedService.setUniqueId(service.getUniqueId());
1853
1854         // TODO Refactor createComponentInstance() method and reduce these mocks
1855         //      not to target the internal details too much
1856         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1857             .thenReturn(Either.left(service));
1858         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1859             .thenReturn(Either.left(originComponent));
1860         when(containerInstanceTypeData.isAllowedForServiceComponent(ResourceTypeEnum.VF, null))
1861             .thenReturn(true);
1862         Mockito.doNothing().when(compositionBusinessLogic).validateAndSetDefaultCoordinates(instanceToBeCreated);
1863         when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1864             .thenReturn(StorageOperationStatus.OK);
1865         when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(service, originComponent, instanceToBeCreated, false, user))
1866             .thenReturn(Either.left(new ImmutablePair<>(updatedService, COMPONENT_INSTANCE_ID)));
1867         when(artifactsBusinessLogic.getArtifacts(
1868             ORIGIN_COMPONENT_ID, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null))
1869             .thenReturn(Either.left(new HashMap<>()));
1870         when(toscaOperationFacade
1871             .addInformationalArtifactsToInstance(service.getUniqueId(), instanceToBeCreated, originComponent.getArtifacts()))
1872             .thenReturn(StorageOperationStatus.OK);
1873         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
1874         when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1875             .thenReturn(StorageOperationStatus.OK);
1876
1877         final ComponentInstance result = componentInstanceBusinessLogic.createComponentInstance(
1878             ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, instanceToBeCreated);
1879         assertThat(result).isEqualTo(instanceToBeCreated);
1880         assertThat(instanceToBeCreated.getComponentVersion()).isEqualTo(originComponent.getVersion());
1881         assertThat(instanceToBeCreated.getIcon()).isEqualTo(originComponent.getIcon());
1882         verify(containerInstanceTypeData, times(1))
1883             .isAllowedForServiceComponent(ResourceTypeEnum.VF, null);
1884         verify(compositionBusinessLogic, times(1)).validateAndSetDefaultCoordinates(instanceToBeCreated);
1885         verify(toscaOperationFacade, times(1))
1886             .addComponentInstanceToTopologyTemplate(service, originComponent, instanceToBeCreated, false, user);
1887         // Check graph db change was committed
1888         verify(janusGraphDao, times(1)).commit();
1889     }
1890     
1891     @Test
1892     void testCreateComponentInstanceServiceSubstitutionSuccess() {
1893         ComponentInstance instanceToBeCreated = createServiceSubstitutionComponentInstance();
1894         Service originService = createServiceSubstitutionOriginService();
1895         Component serviceBaseComponent = createServiceSubstitutionServiceDerivedFromComponent();
1896
1897         Service updatedService = new Service();
1898         updatedService.setComponentInstances(Collections.singletonList(instanceToBeCreated));
1899         updatedService.setUniqueId(service.getUniqueId());
1900         
1901         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1902             .thenReturn(Either.left(service));
1903         when(toscaOperationFacade.getToscaFullElement(ORIGIN_COMPONENT_ID))
1904             .thenReturn(Either.left(originService));
1905         when(toscaOperationFacade.getLatestByToscaResourceName(eq(originService.getDerivedFromGenericType()), isNull()))
1906             .thenReturn(Either.left(serviceBaseComponent));
1907         when(toscaOperationFacade.getToscaElement(eq(ORIGIN_COMPONENT_ID), any(ComponentParametersView.class)))
1908             .thenReturn(Either.left(originService));
1909         Mockito.doNothing().when(compositionBusinessLogic).validateAndSetDefaultCoordinates(instanceToBeCreated);
1910         when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1911             .thenReturn(StorageOperationStatus.OK);
1912         when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(service, serviceBaseComponent, instanceToBeCreated, false, user))
1913             .thenReturn(Either.left(new ImmutablePair<>(updatedService, COMPONENT_INSTANCE_ID)));
1914         when(artifactsBusinessLogic.getArtifacts(
1915                 "baseComponentId", NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null))
1916             .thenReturn(Either.left(new HashMap<>()));
1917         when(toscaOperationFacade
1918             .addInformationalArtifactsToInstance(service.getUniqueId(), instanceToBeCreated, originService.getArtifacts()))
1919             .thenReturn(StorageOperationStatus.OK);
1920         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
1921         when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1922             .thenReturn(StorageOperationStatus.OK);
1923
1924         ComponentInstance result = componentInstanceBusinessLogic.createComponentInstance(
1925             ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, instanceToBeCreated);
1926         assertThat(result).isEqualTo(instanceToBeCreated);
1927         assertThat(instanceToBeCreated.getComponentVersion()).isEqualTo(originService.getVersion());
1928         assertThat(instanceToBeCreated.getIcon()).isEqualTo(originService.getIcon());
1929         verify(compositionBusinessLogic, times(1)).validateAndSetDefaultCoordinates(instanceToBeCreated);
1930         verify(toscaOperationFacade, times(1))
1931             .addComponentInstanceToTopologyTemplate(service, serviceBaseComponent, instanceToBeCreated, false, user);
1932         // Check graph db change was committed
1933         verify(janusGraphDao, times(1)).commit();
1934     }
1935
1936     @Test
1937     void testGetComponentInstanceAttributesById_success() {
1938         final ComponentInstanceAttribute componentInstanceAttribute = new ComponentInstanceAttribute();
1939         componentInstanceAttribute.setComponentInstanceId(TO_INSTANCE_ID);
1940
1941         final HashMap<String, List<ComponentInstanceAttribute>> map = new HashMap<>();
1942         map.put(TO_INSTANCE_ID, Arrays.asList(componentInstanceAttribute));
1943         resource.setComponentInstancesAttributes(map);
1944
1945         final Either<Component, StorageOperationStatus> leftServiceOp = Either.left(resource);
1946         doReturn(leftServiceOp).when(toscaOperationFacade).getToscaElement(COMPONENT_ID);
1947
1948         final List<ComponentInstanceAttribute> result = componentInstanceBusinessLogic
1949             .getComponentInstanceAttributesById(RESOURCE_PARAM_NAME, COMPONENT_ID, TO_INSTANCE_ID, USER_ID);
1950         assertThat(result).isNotNull().isNotEmpty();
1951         verify(toscaOperationFacade, times(1)).getToscaElement(COMPONENT_ID);
1952     }
1953
1954     @Test
1955     void testGetComponentInstanceAttributesById_fail_missing_ComponentInstancesAttributes() {
1956         final Either<Component, StorageOperationStatus> leftServiceOp = Either.left(resource);
1957         doReturn(leftServiceOp).when(toscaOperationFacade).getToscaElement(COMPONENT_ID);
1958
1959         final List<ComponentInstanceAttribute> result = componentInstanceBusinessLogic
1960             .getComponentInstanceAttributesById(RESOURCE_PARAM_NAME, COMPONENT_ID, TO_INSTANCE_ID, USER_ID);
1961         assertThat(result).isNotNull().isEmpty();
1962         verify(toscaOperationFacade, times(1)).getToscaElement(COMPONENT_ID);
1963     }
1964
1965     @Test
1966     void testGetComponentInstanceAttributesById_fail_getToscaElement() {
1967         final ComponentInstanceAttribute componentInstanceAttribute = new ComponentInstanceAttribute();
1968         componentInstanceAttribute.setComponentInstanceId(TO_INSTANCE_ID);
1969
1970         final HashMap<String, List<ComponentInstanceAttribute>> map = new HashMap<>();
1971         map.put(TO_INSTANCE_ID, Arrays.asList(componentInstanceAttribute));
1972         resource.setComponentInstancesAttributes(map);
1973
1974         final Either<Object, StorageOperationStatus> right = Either.right(StorageOperationStatus.BAD_REQUEST);
1975         doReturn(right).when(toscaOperationFacade).getToscaElement(COMPONENT_ID);
1976         doReturn(ActionStatus.BAD_REQUEST_MISSING_RESOURCE).when(componentsUtils).convertFromStorageResponse(StorageOperationStatus.BAD_REQUEST);
1977
1978         assertThrows(ByActionStatusComponentException.class, () -> {
1979             final List<ComponentInstanceAttribute> result = componentInstanceBusinessLogic
1980                 .getComponentInstanceAttributesById(RESOURCE_PARAM_NAME, COMPONENT_ID, TO_INSTANCE_ID, USER_ID);
1981
1982         });
1983
1984     }
1985
1986     @Test
1987     void testGetComponentInstanceAttributesById_fail_getResourceInstanceById() {
1988         final ComponentInstanceAttribute componentInstanceAttribute = new ComponentInstanceAttribute();
1989         componentInstanceAttribute.setComponentInstanceId(TO_INSTANCE_ID);
1990
1991         final HashMap<String, List<ComponentInstanceAttribute>> map = new HashMap<>();
1992         map.put(TO_INSTANCE_ID, Arrays.asList(componentInstanceAttribute));
1993         resource.setComponentInstancesAttributes(map);
1994
1995         final Either<Component, StorageOperationStatus> leftServiceOp = Either.left(resource);
1996         doReturn(leftServiceOp).when(toscaOperationFacade).getToscaElement(COMPONENT_ID);
1997         doReturn(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE).when(componentsUtils).convertFromStorageResponse(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
1998
1999         assertThrows(ByActionStatusComponentException.class, () -> {
2000             final List<ComponentInstanceAttribute> result = componentInstanceBusinessLogic
2001                 .getComponentInstanceAttributesById(RESOURCE_PARAM_NAME, COMPONENT_ID, "", USER_ID);
2002
2003         });
2004
2005     }
2006
2007     @Test
2008     void updateInstanceCapabilitySuccessTest() {
2009         var containerComponentId = "containerComponentId";
2010         var componentInstanceUniqueId = "componentInstanceUniqueId";
2011         var capabilityDefinition = new CapabilityDefinition();
2012         capabilityDefinition.setUniqueId("uniqueId");
2013
2014         final Component component = new Service();
2015         component.setUniqueId(containerComponentId);
2016         component.setLastUpdaterUserId(USER_ID);
2017         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2018
2019         var componentInstance = new ComponentInstance();
2020         componentInstance.setUniqueId(componentInstanceUniqueId);
2021         component.setComponentInstances(Collections.singletonList(componentInstance));
2022
2023         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2024             .thenReturn(Either.left(component));
2025         when(toscaOperationFacade.updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition))
2026             .thenReturn(capabilityDefinition);
2027         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(component))
2028             .thenReturn(Either.left(component));
2029         when(graphLockOperation.lockComponent(containerComponentId, NodeTypeEnum.Service))
2030             .thenReturn(StorageOperationStatus.OK);
2031
2032         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2033             .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, capabilityDefinition, USER_ID);
2034         assertTrue(resultEither.isLeft());
2035         final CapabilityDefinition actualCapabilityDefinition = resultEither.left().value();
2036         assertNotEquals(capabilityDefinition, actualCapabilityDefinition);
2037         assertEquals(capabilityDefinition.getUniqueId(), actualCapabilityDefinition.getUniqueId());
2038     }
2039
2040     @Test
2041     void updateInstanceCapabilityNoContainerComponentTypeTest() {
2042         var responseFormat = new ResponseFormat();
2043         when(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)).thenReturn(responseFormat);
2044         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2045             .updateInstanceCapability(null, "containerComponentId", "componentInstanceUniqueId", new CapabilityDefinition(), USER_ID);
2046         assertTrue(resultEither.isRight(), "Either return should be right");
2047         final ResponseFormat actualResponseFormat = resultEither.right().value();
2048         assertEquals(responseFormat, actualResponseFormat);
2049     }
2050
2051     @Test
2052     void updateInstanceCapabilityContainerComponentNotFoundTest() {
2053         var containerComponentId = "containerComponentId";
2054         when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.right(null));
2055         var responseFormat = new ResponseFormat();
2056         when(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId)).thenReturn(responseFormat);
2057         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2058             .updateInstanceCapability(ComponentTypeEnum.SERVICE, "containerComponentId", "componentInstanceUniqueId", new CapabilityDefinition(), USER_ID);
2059         assertTrue(resultEither.isRight(), "Either return should be right");
2060         final ResponseFormat actualResponseFormat = resultEither.right().value();
2061         assertEquals(responseFormat, actualResponseFormat);
2062     }
2063
2064     @Test
2065     void updateInstanceCapabilityCannotWorkOnComponentTest() {
2066         var containerComponentId = "containerComponentId";
2067         var componentInstanceUniqueId = "componentInstanceUniqueId";
2068
2069         final Component component = new Service();
2070         component.setUniqueId(containerComponentId);
2071         component.setLastUpdaterUserId("anotherUse");
2072         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2073
2074         var expectedResponseFormat = new ResponseFormat();
2075
2076         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2077             .thenReturn(Either.left(component));
2078         when(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION))
2079             .thenReturn(expectedResponseFormat);
2080
2081         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2082             .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, new CapabilityDefinition(), USER_ID);
2083         assertTrue(resultEither.isRight(), "Either return should be right");
2084         final ResponseFormat actualResponseFormat = resultEither.right().value();
2085         assertEquals(expectedResponseFormat, actualResponseFormat);
2086     }
2087
2088     @Test
2089     void updateInstanceCapabilityResourceInstanceNotFoundTest() {
2090         var containerComponentId = "containerComponentId";
2091         var componentInstanceUniqueId = "componentInstanceUniqueId";
2092
2093         final Component component = new Service();
2094         component.setUniqueId(containerComponentId);
2095         component.setLastUpdaterUserId(USER_ID);
2096         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2097
2098         var expectedResponseFormat = new ResponseFormat();
2099
2100         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2101             .thenReturn(Either.left(component));
2102         when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId))
2103             .thenReturn(expectedResponseFormat);
2104
2105         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2106             .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, new CapabilityDefinition(), USER_ID);
2107         assertTrue(resultEither.isRight(), "Either return should be right");
2108         final ResponseFormat actualResponseFormat = resultEither.right().value();
2109         assertEquals(expectedResponseFormat, actualResponseFormat);
2110     }
2111
2112     @Test
2113     void updateInstanceCapabilityUpdateMetadataFailTest() {
2114         var containerComponentId = "containerComponentId";
2115         var componentInstanceUniqueId = "componentInstanceUniqueId";
2116         var capabilityDefinition = new CapabilityDefinition();
2117         capabilityDefinition.setUniqueId("uniqueId");
2118
2119         final Component component = new Service();
2120         component.setUniqueId(containerComponentId);
2121         component.setLastUpdaterUserId(USER_ID);
2122         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2123
2124         var componentInstance = new ComponentInstance();
2125         componentInstance.setUniqueId(componentInstanceUniqueId);
2126         component.setComponentInstances(Collections.singletonList(componentInstance));
2127
2128         var expectedResponseFormat = new ResponseFormat();
2129
2130         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2131             .thenReturn(Either.left(component));
2132         when(graphLockOperation.lockComponent(containerComponentId, NodeTypeEnum.Service))
2133             .thenReturn(StorageOperationStatus.OK);
2134         when(toscaOperationFacade.updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition))
2135             .thenReturn(capabilityDefinition);
2136         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(component))
2137             .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
2138         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR, ComponentTypeEnum.SERVICE))
2139             .thenReturn(ActionStatus.GENERAL_ERROR);
2140         when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR))
2141             .thenReturn(expectedResponseFormat);
2142
2143         final Either<CapabilityDefinition, ResponseFormat> resultEither = componentInstanceBusinessLogic
2144             .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, capabilityDefinition, USER_ID);
2145         assertTrue(resultEither.isRight(), "Either return should be right");
2146         final ResponseFormat actualResponseFormat = resultEither.right().value();
2147         assertEquals(expectedResponseFormat, actualResponseFormat);
2148     }
2149
2150     @Test
2151     void updateInstanceCapabilityBusinessExceptionHandlingTest() {
2152         var containerComponentId = "containerComponentId";
2153         var componentInstanceUniqueId = "componentInstanceUniqueId";
2154         var capabilityDefinition = new CapabilityDefinition();
2155         capabilityDefinition.setUniqueId("uniqueId");
2156
2157         final Component component = new Service();
2158         component.setUniqueId(containerComponentId);
2159         component.setLastUpdaterUserId(USER_ID);
2160         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2161
2162         var componentInstance = new ComponentInstance();
2163         componentInstance.setUniqueId(componentInstanceUniqueId);
2164         component.setComponentInstances(Collections.singletonList(componentInstance));
2165
2166
2167         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2168             .thenReturn(Either.left(component));
2169         when(graphLockOperation.lockComponent(containerComponentId, NodeTypeEnum.Service))
2170             .thenReturn(StorageOperationStatus.OK);
2171         when(toscaOperationFacade.updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition))
2172             .thenThrow(new OperationException(ActionStatus.GENERAL_ERROR));
2173
2174         final BusinessException businessException = assertThrows(BusinessException.class, () -> {
2175             componentInstanceBusinessLogic
2176                 .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, capabilityDefinition, USER_ID);
2177         });
2178         assertTrue(businessException instanceof OperationException);
2179         assertEquals(ActionStatus.GENERAL_ERROR, ((OperationException) businessException).getActionStatus());
2180     }
2181
2182     @Test
2183     void updateInstanceCapabilityUnknownExceptionHandlingTest() {
2184         var containerComponentId = "containerComponentId";
2185         var componentInstanceUniqueId = "componentInstanceUniqueId";
2186         var capabilityDefinition = new CapabilityDefinition();
2187         capabilityDefinition.setUniqueId("uniqueId");
2188
2189         final Component component = new Service();
2190         component.setUniqueId(containerComponentId);
2191         component.setLastUpdaterUserId(USER_ID);
2192         component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2193
2194         var componentInstance = new ComponentInstance();
2195         componentInstance.setUniqueId(componentInstanceUniqueId);
2196         component.setComponentInstances(Collections.singletonList(componentInstance));
2197
2198         var expectedResponseFormat = new ResponseFormat();
2199
2200         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
2201             .thenReturn(Either.left(component));
2202         when(graphLockOperation.lockComponent(containerComponentId, NodeTypeEnum.Service))
2203             .thenReturn(StorageOperationStatus.OK);
2204         when(toscaOperationFacade.updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition))
2205             .thenThrow(new RuntimeException());
2206         when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR))
2207             .thenReturn(expectedResponseFormat);
2208
2209         final Exception exception = assertThrows(BusinessException.class, () ->
2210             componentInstanceBusinessLogic
2211                 .updateInstanceCapability(ComponentTypeEnum.SERVICE, containerComponentId, componentInstanceUniqueId, capabilityDefinition, USER_ID));
2212         assertTrue(exception instanceof ByResponseFormatComponentException);
2213         final ByResponseFormatComponentException actualException = (ByResponseFormatComponentException) exception;
2214         assertEquals(expectedResponseFormat, actualException.getResponseFormat());
2215     }
2216
2217     private ComponentInstance createServiceSubstitutionComponentInstance() {
2218         final ComponentInstance instanceToBeCreated = new ComponentInstance();
2219         instanceToBeCreated.setName(COMPONENT_INSTANCE_NAME);
2220         instanceToBeCreated.setUniqueId(COMPONENT_INSTANCE_ID);
2221         instanceToBeCreated.setComponentUid(ORIGIN_COMPONENT_ID);
2222         instanceToBeCreated.setOriginType(OriginTypeEnum.ServiceSubstitution);
2223
2224         return instanceToBeCreated;
2225     }
2226     
2227     private Service createServiceSubstitutionOriginService() {
2228         final Service originComponent = new Service();
2229         originComponent.setLifecycleState(LifecycleStateEnum.CERTIFIED);
2230         originComponent.setVersion(ORIGIN_COMPONENT_VERSION);
2231         originComponent.setIcon(ICON_NAME);
2232         originComponent.setDerivedFromGenericType("org.openecomp.resource.abstract.nodes.service");
2233         originComponent.setName("myService");
2234         return originComponent;
2235     }
2236     
2237     private Component createServiceSubstitutionServiceDerivedFromComponent() {
2238         final Resource component = new Resource();
2239         component.setLifecycleState(LifecycleStateEnum.CERTIFIED);
2240         component.setVersion(ORIGIN_COMPONENT_VERSION);
2241         component.setIcon(ICON_NAME);
2242         component.setToscaResourceName("org.openecomp.resource.abstract.nodes.service");
2243         component.setUniqueId("baseComponentId");
2244         return component;
2245     }
2246
2247 }
2248