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