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