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