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