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