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