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