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