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