Config. allowed instances in component composition
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / ComponentInstanceBusinessLogicTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.jupiter.api.Assertions.assertEquals;
25 import static org.junit.jupiter.api.Assertions.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.datatypes.elements.CapabilityDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
75 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
76 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
77 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
79 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
80 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
81 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
82 import org.openecomp.sdc.be.impl.ComponentsUtils;
83 import org.openecomp.sdc.be.model.ArtifactDefinition;
84 import org.openecomp.sdc.be.model.CapabilityDefinition;
85 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
86 import org.openecomp.sdc.be.model.Component;
87 import org.openecomp.sdc.be.model.ComponentInstance;
88 import org.openecomp.sdc.be.model.ComponentInstanceInput;
89 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
90 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
91 import org.openecomp.sdc.be.model.ComponentParametersView;
92 import org.openecomp.sdc.be.model.DataTypeDefinition;
93 import org.openecomp.sdc.be.model.InputDefinition;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.PolicyDefinition;
96 import org.openecomp.sdc.be.model.RelationshipImpl;
97 import org.openecomp.sdc.be.model.RelationshipInfo;
98 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
99 import org.openecomp.sdc.be.model.RequirementDefinition;
100 import org.openecomp.sdc.be.model.Resource;
101 import org.openecomp.sdc.be.model.Service;
102 import org.openecomp.sdc.be.model.User;
103 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
104 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
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         resource = createResource();
657     }
658
659     private Resource createResource() {
660         final Resource 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         return resource;
669     }
670
671     private void createService() {
672         service = new Service();
673         service.setUniqueId(COMPONENT_ID);
674         service.setComponentInstancesRelations(Lists.newArrayList(relation));
675         service.setComponentInstances(Lists.newArrayList(toInstance, fromInstance));
676         service.setCapabilities(toInstance.getCapabilities());
677         service.setRequirements(fromInstance.getRequirements());
678         service.setComponentType(ComponentTypeEnum.SERVICE);
679         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
680         service.setLastUpdaterUserId(USER_ID);
681
682         Map<String, List<ComponentInstanceProperty>> ciPropertyMap = new HashMap<>();
683         ciPropertyMap.put(TO_INSTANCE_ID, ciPropertyList);
684         service.setComponentInstancesProperties(ciPropertyMap);
685
686         Map<String, List<ComponentInstanceInput>> ciInputMap = new HashMap<>();
687         ciInputMap.put(TO_INSTANCE_ID, ciInputList);
688         service.setComponentInstancesInputs(ciInputMap);
689     }
690
691     private void createInstances() {
692         toInstance = new ComponentInstance();
693         toInstance.setUniqueId(TO_INSTANCE_ID);
694         toInstance.setName(TO_INSTANCE_NAME);
695
696         fromInstance = new ComponentInstance();
697         fromInstance.setUniqueId(FROM_INSTANCE_ID);
698
699         CapabilityDataDefinition capability = new CapabilityDataDefinition();
700         capability.setOwnerId(CAPABILITY_OWNER_ID);
701         capability.setUniqueId(CAPABILITY_UID);
702         capability.setName(CAPABILITY_NAME);
703
704         Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
705         final CapabilityDefinition capabilityDefinition = new CapabilityDefinition(capability);
706         final ArrayList<ComponentInstanceProperty> properties = new ArrayList<>();
707         properties.add(componentInstancePropInput);
708         capabilityDefinition.setProperties(properties);
709         capabilities.put(capability.getName(), Lists.newArrayList(capabilityDefinition));
710
711         RequirementDataDefinition requirement = new RequirementDataDefinition();
712         requirement.setOwnerId(REQUIREMENT_OWNER_ID);
713         requirement.setUniqueId(REQUIREMENT_UID);
714         requirement.setName(REQUIREMENT_NAME);
715         requirement.setRelationship(RELATIONSHIP_TYPE);
716
717         Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
718         requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement)));
719
720         toInstance.setCapabilities(capabilities);
721         fromInstance.setRequirements(requirements);
722
723     }
724
725     private void createRelation() {
726
727         relation = new RequirementCapabilityRelDef();
728         CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
729         RelationshipInfo relationInfo = new RelationshipInfo();
730         relationInfo.setId(RELATION_ID);
731         relationship.setRelation(relationInfo);
732
733         relation.setRelationships(Lists.newArrayList(relationship));
734         relation.setToNode(TO_INSTANCE_ID);
735         relation.setFromNode(FROM_INSTANCE_ID);
736
737         relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID);
738         relationInfo.setCapabilityUid(CAPABILITY_UID);
739         relationInfo.setCapability(CAPABILITY_NAME);
740         relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID);
741         relationInfo.setRequirementUid(REQUIREMENT_UID);
742         relationInfo.setRequirement(REQUIREMENT_NAME);
743         RelationshipImpl relationshipImpl = new RelationshipImpl();
744         relationshipImpl.setType(RELATIONSHIP_TYPE);
745         relationInfo.setRelationships(relationshipImpl);
746     }
747
748     private void createProperties() {
749         // Create GetInputValueData
750         GetInputValueDataDefinition inputValueDef = new GetInputValueDataDefinition();
751         inputValueDef.setInputId(INPUT_ID);
752         List<GetInputValueDataDefinition> inputValueDefList = new ArrayList<>();
753         inputValueDefList.add(inputValueDef);
754         // Create ComponentInstanceProperty
755         ComponentInstanceProperty ciProperty = new ComponentInstanceProperty();
756         ciProperty.setGetInputValues(inputValueDefList);
757         ciProperty.setName(PROP_NAME);
758         // Create ComponentInstanceProperty list
759         ciPropertyList = new ArrayList<>();
760         ciPropertyList.add(ciProperty);
761     }
762
763     private void createInputs() {
764         // Create GetInputValueData
765         GetInputValueDataDefinition inputValueDef = new GetInputValueDataDefinition();
766         inputValueDef.setInputId(INPUT_ID);
767         List<GetInputValueDataDefinition> inputValueDefList = new ArrayList<>();
768         inputValueDefList.add(inputValueDef);
769         // Create ComponentInstanceInput
770         ComponentInstanceInput ciInput = new ComponentInstanceInput();
771         ciInput.setUniqueId(INPUT_ID);
772         ciInput.setName(PROP_NAME);
773         ciInput.setGetInputValues(inputValueDefList);
774         // Create ComponentInstanceInput list
775         ciInputList = new ArrayList<>();
776         ciInputList.add(ciInput);
777     }
778
779     private ComponentInstanceBusinessLogic createTestSubject() {
780         return componentInstanceBusinessLogic;
781     }
782
783     @Test
784     void testChangeServiceProxyVersion() {
785         ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
786
787         Either<ComponentInstance, ResponseFormat> result;
788
789         // default test
790         componentInstanceBusinessLogic = createTestSubject();
791         result = componentInstanceBusinessLogic.changeServiceProxyVersion();
792         assertNotNull(result);
793     }
794
795     @Test
796     void testCreateServiceProxy() {
797         ComponentInstanceBusinessLogic testSubject;
798         Either<ComponentInstance, ResponseFormat> result;
799
800         // default test
801         testSubject = createTestSubject();
802         result = testSubject.createServiceProxy();
803         assertNotNull(result);
804     }
805
806     @Test
807     void testDeleteServiceProxy() {
808         ComponentInstanceBusinessLogic testSubject;
809
810         Either<ComponentInstance, ResponseFormat> result;
811
812         // default test
813         testSubject = createTestSubject();
814         result = testSubject.deleteServiceProxy();
815         assertNotNull(result);
816     }
817
818     @Test
819     void testGetComponentInstanceInputsByInputIdEmpty() {
820         Component component = new Service();
821         String inputId = "";
822         List<ComponentInstanceInput> result;
823
824         result = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId);
825         assertNotNull(result);
826         assertThat(result.isEmpty()).isTrue();
827     }
828
829     @Test
830     void testGetComponentInstanceInputsByInputIdPresent() {
831         List<ComponentInstanceInput> result;
832
833         result = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(service, INPUT_ID);
834         assertNotNull(result);
835         assertThat(result.isEmpty()).isFalse();
836         assertThat(result.size()).isOne();
837         ComponentInstanceInput resultInput = result.get(0);
838         assertThat(resultInput.getComponentInstanceId()).isEqualTo(TO_INSTANCE_ID);
839         assertThat(resultInput.getComponentInstanceName()).isEqualTo(TO_INSTANCE_NAME);
840     }
841
842     @Test
843     void testGetComponentInstancePropertiesByInputIdEmpty() {
844         Component component = new Service();
845         String inputId = "";
846         List<ComponentInstanceProperty> result;
847
848         result = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId);
849         assertNotNull(result);
850         assertThat(result.isEmpty()).isTrue();
851     }
852
853     @Test
854     void testGetComponentInstancePropertiesByInputIdPresent() {
855         List<ComponentInstanceProperty> result;
856
857         result = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(service, INPUT_ID);
858         assertNotNull(result);
859         assertThat(result.size()).isOne();
860         ComponentInstanceProperty resultProperty = result.get(0);
861         assertThat(resultProperty.getComponentInstanceId()).isEqualTo(TO_INSTANCE_ID);
862         assertThat(resultProperty.getComponentInstanceName()).isEqualTo(TO_INSTANCE_NAME);
863     }
864
865     @Test
866     void testGetRelationById() {
867         ComponentInstanceBusinessLogic testSubject;
868         String componentId = "";
869         String relationId = "";
870         String userId = user.getUserId();
871         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE_INSTANCE;
872         Either<RequirementCapabilityRelDef, ResponseFormat> result;
873
874         // default test
875         testSubject = createTestSubject();
876         result = testSubject.getRelationById(componentId, relationId, userId, componentTypeEnum);
877         assertNotNull(result);
878     }
879
880     @Test
881     void testValidateParent() {
882         ComponentInstanceBusinessLogic testSubject;
883         resource = createResource();
884         String nodeTemplateId = "";
885         boolean result;
886
887         // default test
888         testSubject = createTestSubject();
889         result = Deencapsulation.invoke(testSubject, "validateParent", new Object[]{resource, nodeTemplateId});
890         assertNotNull(result);
891     }
892
893     @Test
894     void testGetComponentType() {
895         ComponentInstanceBusinessLogic testSubject;
896         ComponentTypeEnum result;
897
898         // default test
899         testSubject = createTestSubject();
900         result = Deencapsulation.invoke(testSubject, "getComponentType", new Object[]{ComponentTypeEnum.class});
901         assertNotNull(result);
902     }
903
904     @Test
905     void testGetNewGroupName() {
906         ComponentInstanceBusinessLogic testSubject;
907         String oldPrefix = "";
908         String newNormailzedPrefix = "";
909         String qualifiedGroupInstanceName = "";
910         String result;
911
912         // test 1
913         testSubject = createTestSubject();
914         result = Deencapsulation.invoke(testSubject, "getNewGroupName",
915             new Object[]{oldPrefix, newNormailzedPrefix, qualifiedGroupInstanceName});
916         assertNotNull(result);
917     }
918
919     @Test
920     void testUpdateComponentInstanceMetadata_3() {
921         ComponentInstanceBusinessLogic testSubject;
922         createInstances();
923         ComponentInstance result;
924
925         // default test
926         testSubject = createTestSubject();
927         result = Deencapsulation
928             .invoke(testSubject, "updateComponentInstanceMetadata", new Object[]{toInstance, toInstance});
929         assertNotNull(result);
930     }
931
932     @Test
933     void testFindRelation() {
934         ComponentInstanceBusinessLogic testSubject;
935         String relationId = "";
936         List<RequirementCapabilityRelDef> requirementCapabilityRelations = new ArrayList<>();
937         RequirementCapabilityRelDef result;
938
939         // default test
940         testSubject = createTestSubject();
941         result = Deencapsulation.invoke(testSubject, "findRelation",
942             new Object[]{relationId, requirementCapabilityRelations});
943     }
944
945     @Test
946     void testCreateOrUpdatePropertiesValues() {
947         ComponentInstanceBusinessLogic testSubject;
948         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
949         resource = createResource();
950         String componentId = resource.getUniqueId();
951         String resourceInstanceId = "";
952         List<ComponentInstanceProperty> properties = new ArrayList<>();
953         String userId = user.getUserId();
954         Either<List<ComponentInstanceProperty>, ResponseFormat> result;
955
956         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll))
957             .thenReturn(Either.left(resource));
958
959         // test 1
960         testSubject = createTestSubject();
961         result = testSubject
962             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
963                 userId);
964         assertNotNull(result);
965
966         componentTypeEnum = null;
967         result = testSubject
968             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
969                 userId);
970         assertNotNull(result);
971
972         result = testSubject
973             .createOrUpdatePropertiesValues(componentTypeEnum, componentId, resourceInstanceId, properties,
974                 userId);
975         assertNotNull(result);
976     }
977
978     @Test
979     void testUpdateCapabilityPropertyOnContainerComponent() {
980         ComponentInstanceBusinessLogic testSubject;
981         ComponentInstanceProperty property = new ComponentInstanceProperty();
982         String newValue = "";
983         resource = createResource();
984         createInstances();
985         String capabilityType = "";
986         String capabilityName = "";
987         ResponseFormat result;
988
989         // default test
990         testSubject = createTestSubject();
991         result = Deencapsulation.invoke(testSubject, "updateCapabilityPropertyOnContainerComponent",
992             new Object[]{property, newValue, resource, toInstance, capabilityType, capabilityName});
993     }
994
995     @Test
996     void testCreateOrUpdateInstanceInputValues() {
997         ComponentInstanceBusinessLogic testSubject;
998         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
999         resource = createResource();
1000         String componentId = resource.getUniqueId();
1001         String resourceInstanceId = "";
1002         List<ComponentInstanceInput> inputs = new ArrayList<>();
1003         String userId = user.getUserId();
1004         Either<List<ComponentInstanceInput>, ResponseFormat> result;
1005
1006         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll))
1007             .thenReturn(Either.left(resource));
1008
1009         // test 1
1010         testSubject = createTestSubject();
1011         result = testSubject
1012             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1013                 userId);
1014         assertNotNull(result);
1015         componentTypeEnum = null;
1016         result = testSubject
1017             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1018                 userId);
1019         assertNotNull(result);
1020
1021         result = testSubject
1022             .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, resourceInstanceId, inputs,
1023                 userId);
1024         assertNotNull(result);
1025     }
1026
1027     @Test
1028     void testCreateOrUpdateGroupInstancePropertyValue() {
1029         ComponentInstanceBusinessLogic testSubject;
1030         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1031         resource = createResource();
1032         String componentId = resource.getUniqueId();
1033         String resourceInstanceId = "";
1034         String groupInstanceId = "";
1035         ComponentInstanceProperty property = new ComponentInstanceProperty();
1036         String userId = user.getUserId();
1037         Either<ComponentInstanceProperty, ResponseFormat> result;
1038
1039         when(toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata))
1040             .thenReturn(Either.left(resource));
1041
1042         // test 1
1043         testSubject = createTestSubject();
1044         result = testSubject
1045             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1046                 groupInstanceId, property, userId);
1047         assertNotNull(result);
1048         componentTypeEnum = null;
1049         result = testSubject
1050             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1051                 groupInstanceId, property, userId);
1052         assertNotNull(result);
1053
1054         result = testSubject
1055             .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, resourceInstanceId,
1056                 groupInstanceId, property, userId);
1057         assertNotNull(result);
1058     }
1059
1060     @Test
1061     void testDeletePropertyValue() {
1062         ComponentInstanceBusinessLogic testSubject;
1063         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1064         createService();
1065         String serviceId = service.getUniqueId();
1066         String resourceInstanceId = "";
1067         String propertyValueId = "";
1068         String userId = user.getUserId();
1069         Either<ComponentInstanceProperty, ResponseFormat> result;
1070
1071         when(toscaOperationFacade.getToscaElement(serviceId, JsonParseFlagEnum.ParseMetadata))
1072             .thenReturn(Either.left(service));
1073
1074         // test 1
1075         testSubject = createTestSubject();
1076         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1077             userId);
1078         assertNotNull(result);
1079         componentTypeEnum = null;
1080         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1081             userId);
1082         assertNotNull(result);
1083
1084         result = testSubject.deletePropertyValue(componentTypeEnum, serviceId, resourceInstanceId, propertyValueId,
1085             userId);
1086         assertNotNull(result);
1087     }
1088
1089     @Test
1090     void testGetComponentParametersViewForForwardingPath() {
1091         ComponentInstanceBusinessLogic testSubject;
1092         ComponentParametersView result;
1093
1094         // default test
1095         testSubject = createTestSubject();
1096         result = Deencapsulation.invoke(testSubject, "getComponentParametersViewForForwardingPath");
1097         assertNotNull(result);
1098     }
1099
1100     @Test
1101     void testGetResourceInstanceById() {
1102         ComponentInstanceBusinessLogic testSubject;
1103         resource = createResource();
1104         String instanceId = "";
1105         Either<ComponentInstance, StorageOperationStatus> result;
1106
1107         // default test
1108         testSubject = createTestSubject();
1109         result = Deencapsulation.invoke(testSubject, "getResourceInstanceById", new Object[]{resource, instanceId});
1110         assertNotNull(result);
1111     }
1112
1113     @Test
1114     void testUpdateInstanceCapabilityProperties_1() {
1115         ComponentInstanceBusinessLogic testSubject;
1116         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
1117         resource = createResource();
1118         String containerComponentId = resource.getUniqueId();
1119         String componentInstanceUniqueId = "";
1120         String capabilityType = "";
1121         String capabilityName = "";
1122         List<ComponentInstanceProperty> properties = new ArrayList<>();
1123         String userId = user.getUserId();
1124         Either<List<ComponentInstanceProperty>, ResponseFormat> result;
1125
1126         when(toscaOperationFacade.getToscaFullElement(containerComponentId))
1127             .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
1128         // test 1
1129         testSubject = createTestSubject();
1130         result = testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId,
1131             componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
1132         assertNotNull(result);
1133         when(toscaOperationFacade.getToscaFullElement(containerComponentId)).thenReturn(Either.left(resource));
1134         result = testSubject.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId,
1135             componentInstanceUniqueId, capabilityType, capabilityName, properties, userId);
1136         assertNotNull(result);
1137     }
1138
1139     @Test
1140     void testCopyComponentInstanceWrongUserId() {
1141
1142         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1143         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1144         String containerComponentId = service.getUniqueId();
1145         String componentInstanceId = resource.getUniqueId();
1146         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1147         service.setLastUpdaterUserId("wrong user id");
1148
1149         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1150         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1151         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1152             .thenReturn(leftServiceOp);
1153         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1154         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1155             .thenReturn(StorageOperationStatus.OK);
1156         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1157             .thenReturn(StorageOperationStatus.OK);
1158
1159         result = componentInstanceBusinessLogic
1160             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId,
1161                 USER_ID);
1162         assertNotNull(result);
1163
1164         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1165         assertThat(result.isRight()).isTrue();
1166     }
1167
1168     @Test
1169     void testCopyComponentInstanceComponentWrongState() {
1170         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1171         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1172         String containerComponentId = service.getUniqueId();
1173         String componentInstanceId = resource.getUniqueId();
1174         String oldServiceLastUpdatedUserId = service.getLastUpdaterUserId();
1175         service.setLastUpdaterUserId(USER_ID);
1176
1177         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1178         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1179         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1180             .thenReturn(leftServiceOp);
1181         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1182         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1183             .thenReturn(StorageOperationStatus.OK);
1184         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1185             .thenReturn(StorageOperationStatus.OK);
1186         result = componentInstanceBusinessLogic
1187             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId, USER_ID);
1188         assertNotNull(result);
1189         service.setLastUpdaterUserId(oldServiceLastUpdatedUserId);
1190         assertThat(result.isRight()).isTrue();
1191     }
1192
1193     @Test
1194     void testCopyComponentInstance() {
1195         Either<Map<String, ComponentInstance>, ResponseFormat> result;
1196         ComponentInstance inputComponentInstance = createComponetInstanceFromComponent(resource);
1197         String containerComponentId = service.getUniqueId();
1198         String componentInstanceId = resource.getUniqueId();
1199         String oldServiceLastUpdatedUserId = service.getLastUpdaterUserId();
1200         service.setLastUpdaterUserId(USER_ID);
1201         LifecycleStateEnum oldResourceLifeCycle = resource.getLifecycleState();
1202         resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1203
1204         Either<Component, StorageOperationStatus> leftServiceOp = Either.left(service);
1205         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(leftServiceOp);
1206         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1207             .thenReturn(leftServiceOp);
1208         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1209             .thenReturn(StorageOperationStatus.OK);
1210         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1211             .thenReturn(StorageOperationStatus.OK);
1212
1213         result = componentInstanceBusinessLogic
1214             .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId,
1215                 USER_ID);
1216         assertNotNull(result);
1217
1218         service.setLastUpdaterUserId(oldServiceLastUpdatedUserId);
1219         resource.setLifecycleState(oldResourceLifeCycle);
1220
1221         assertThat(result.isLeft()).isFalse();
1222     }
1223
1224     @Test
1225     void testCreateOrUpdateAttributeValueForCopyPaste() {
1226         ComponentInstance serviceComponentInstance = createComponetInstanceFromComponent(service);
1227         ComponentInstanceProperty attribute = new ComponentInstanceProperty();
1228         attribute.setType("string");
1229         attribute.setUniqueId("testCreateOrUpdateAttributeValueForCopyPaste");
1230         SchemaDefinition def = Mockito.mock(SchemaDefinition.class);
1231         attribute.setSchema(def);
1232         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1233         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1234         service.setLastUpdaterUserId(USER_ID);
1235         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1236
1237         Map<String, List<ComponentInstanceProperty>> instAttrsMap = new HashMap<>();
1238         List<ComponentInstanceProperty> instAttrsList = new ArrayList<>();
1239         ComponentInstanceProperty prop = new ComponentInstanceProperty();
1240         prop.setUniqueId(attribute.getUniqueId());
1241         instAttrsList.add(prop);
1242         instAttrsMap.put(toInstance.getUniqueId(), instAttrsList);
1243         service.setComponentInstancesAttributes(instAttrsMap);
1244
1245         Either<Component, StorageOperationStatus> serviceEitherLeft = Either.left(service);
1246         when(toscaOperationFacade.getToscaElement(serviceComponentInstance.getUniqueId(), JsonParseFlagEnum.ParseAll))
1247             .thenReturn(serviceEitherLeft);
1248         when(toscaOperationFacade.updateComponentInstanceAttribute(service, toInstance.getUniqueId(), attribute))
1249             .thenReturn(StorageOperationStatus.OK);
1250         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(service))
1251             .thenReturn(serviceEitherLeft);
1252
1253         Either<ComponentInstanceProperty, ResponseFormat> result = Deencapsulation
1254             .invoke(componentInstanceBusinessLogic,
1255                 "createOrUpdateAttributeValueForCopyPaste",
1256                 ComponentTypeEnum.SERVICE,
1257                 serviceComponentInstance
1258                     .getUniqueId(),
1259                 toInstance.getUniqueId(), attribute,
1260                 USER_ID);
1261         assertNotNull(result);
1262
1263         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1264         service.setLifecycleState(oldLifeCycleState);
1265
1266         assertThat(result.isLeft()).isTrue();
1267         ComponentInstanceProperty resultProp = result.left().value();
1268         assertEquals(resultProp.getPath().size(), 1);
1269         assertEquals(resultProp.getPath().get(0), toInstance.getUniqueId());
1270     }
1271
1272     @Test
1273     void testUpdateComponentInstanceProperty() {
1274
1275         String containerComponentId = service.getUniqueId();
1276         String componentInstanceId = "dummy_id";
1277         ComponentInstanceProperty property = Mockito.mock(ComponentInstanceProperty.class);
1278
1279         Either<Component, StorageOperationStatus> getComponent = Either.left(service);
1280         when(toscaOperationFacade.getToscaElement(containerComponentId)).thenReturn(getComponent);
1281         StorageOperationStatus status = StorageOperationStatus.OK;
1282         when(toscaOperationFacade.updateComponentInstanceProperty(service, componentInstanceId, property))
1283             .thenReturn(status);
1284         Either<Component, StorageOperationStatus> updateContainerRes = Either.left(service);
1285         when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(service))
1286             .thenReturn(updateContainerRes);
1287
1288         Either<String, ResponseFormat> result = Deencapsulation.invoke(componentInstanceBusinessLogic,
1289             "updateComponentInstanceProperty", containerComponentId, componentInstanceId, property);
1290         assertNotNull(result);
1291         assertThat(result.isLeft()).isTrue();
1292     }
1293
1294     @Test
1295     void testGetInputListDefaultValue() {
1296         Component component = service;
1297         String inputId = "dummy_id";
1298         String defaultValue = "dummy_default_value";
1299         List<InputDefinition> newInputs = new ArrayList<>();
1300         InputDefinition in = new InputDefinition();
1301         in.setUniqueId(inputId);
1302         in.setDefaultValue(defaultValue);
1303         newInputs.add(in);
1304         List<InputDefinition> oldInputs = service.getInputs();
1305         service.setInputs(newInputs);
1306
1307         Either<String, ResponseFormat> result =
1308             Deencapsulation.invoke(componentInstanceBusinessLogic, "getInputListDefaultValue", component, inputId);
1309
1310         service.setInputs(oldInputs);
1311
1312         assertEquals(result.left().value(), defaultValue);
1313     }
1314
1315     @Test
1316     void testBatchDeleteComponentInstanceFailureWrongType() {
1317         Map<String, List<String>> result;
1318         List<String> componentInstanceIdList = new ArrayList<>();
1319         String containerComponentParam = "WRONG_TYPE";
1320         String containerComponentId = "containerComponentId";
1321         String componentInstanceId = "componentInstanceId";
1322         componentInstanceIdList.add(componentInstanceId);
1323         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1324         List<String> deleteErrorIds = new ArrayList<>();
1325         deleteErrorIds.add(componentInstanceId);
1326         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1327         Either<Component, StorageOperationStatus> cont = Either.left(service);
1328         when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(null)))
1329             .thenReturn(ActionStatus.GENERAL_ERROR);
1330         when(toscaOperationFacade.getToscaElement(any(String.class), any(ComponentParametersView.class)))
1331             .thenReturn(cont);
1332
1333         try {
1334             result = componentInstanceBusinessLogic
1335                 .batchDeleteComponentInstance(containerComponentParam, containerComponentId, componentInstanceIdList,
1336                     USER_ID);
1337             assertNotNull(result);
1338             assertEquals(deleteErrorMap, result);
1339         } catch (ComponentException e) {
1340             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1341         }
1342     }
1343
1344     @Test
1345     void testBatchDeleteComponentInstanceFailureCompIds() {
1346         String containerComponentParam = ComponentTypeEnum.SERVICE_PARAM_NAME;
1347         String containerComponentId = "containerComponentId";
1348         String componentInstanceId = "componentInstanceId";
1349         List<String> componentInstanceIdList = new ArrayList<>();
1350         componentInstanceIdList.add(componentInstanceId);
1351         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1352         List<String> deleteErrorIds = new ArrayList<>();
1353         deleteErrorIds.add(componentInstanceId);
1354         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1355
1356         Either<Component, StorageOperationStatus> err = Either.right(StorageOperationStatus.GENERAL_ERROR);
1357         when(toscaOperationFacade.getToscaElement(eq(containerComponentId), any(ComponentParametersView.class)))
1358             .thenReturn(err);
1359
1360         try {
1361             Map<String, List<String>> result = componentInstanceBusinessLogic.batchDeleteComponentInstance(
1362                 containerComponentParam, containerComponentId, componentInstanceIdList, USER_ID);
1363             assertNotNull(result);
1364             assertEquals(deleteErrorMap, result);
1365         } catch (ComponentException e) {
1366             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1367         }
1368     }
1369
1370     @Test
1371     void testBatchDeleteComponentInstanceSuccess() {
1372         Map<String, List<String>> result;
1373         String containerComponentParam = ComponentTypeEnum.SERVICE_PARAM_NAME;
1374         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1375         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1376         service.setLastUpdaterUserId(USER_ID);
1377         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1378         String containerComponentId = service.getUniqueId();
1379         String componentInstanceId = TO_INSTANCE_ID;
1380         List<String> componentInstanceIdList = new ArrayList<>();
1381         componentInstanceIdList.add(componentInstanceId);
1382         Map<String, List<String>> deleteErrorMap = new HashMap<>();
1383         List<String> deleteErrorIds = new ArrayList<>();
1384         deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
1385
1386         Either<Component, StorageOperationStatus> cont = Either.left(service);
1387         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1388             .thenReturn(StorageOperationStatus.OK);
1389         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1390             .thenReturn(StorageOperationStatus.OK);
1391         ImmutablePair<Component, String> pair = new ImmutablePair<>(resource, TO_INSTANCE_ID);
1392         Either<ImmutablePair<Component, String>, StorageOperationStatus> result2 = Either.left(pair);
1393         when(toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(service, componentInstanceId))
1394             .thenReturn(result2);
1395         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1396             .thenReturn(cont);
1397         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
1398
1399         result = componentInstanceBusinessLogic
1400             .batchDeleteComponentInstance(containerComponentParam, containerComponentId,
1401                 componentInstanceIdList, USER_ID);
1402         assertNotNull(result);
1403
1404         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1405         service.setLifecycleState(oldLifeCycleState);
1406         assertEquals(deleteErrorMap, result);
1407     }
1408
1409     @Test
1410     void testDissociateRIFromRIFailDissociate() {
1411
1412         List<RequirementCapabilityRelDef> result;
1413         RequirementCapabilityRelDef ref = new RequirementCapabilityRelDef();
1414         ref.setFromNode(FROM_INSTANCE_ID);
1415         ref.setToNode(TO_INSTANCE_ID);
1416         List<CapabilityRequirementRelationship> relationships = new ArrayList<>();
1417         CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
1418         RelationshipInfo ri = new RelationshipInfo();
1419         ri.setRequirement(REQUIREMENT_NAME);
1420         relationship.setRelation(ri);
1421         relationships.add(relationship);
1422         ref.setRelationships(relationships);
1423         List<RequirementCapabilityRelDef> requirementDefList = new ArrayList<>();
1424         requirementDefList.add(ref);
1425         ComponentTypeEnum componentTypeEnum = service.getComponentType();
1426         String componentId = service.getUniqueId();
1427         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1428         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1429         service.setLastUpdaterUserId(USER_ID);
1430         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1431
1432         Either<Component, StorageOperationStatus> cont = Either.left(service);
1433         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1434             .thenReturn(cont);
1435         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1436             .thenReturn(StorageOperationStatus.OK);
1437         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1438             .thenReturn(StorageOperationStatus.OK);
1439         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultEither;
1440         resultEither = Either.right(StorageOperationStatus.OK);
1441         when(componentsUtils.convertFromStorageResponseForResourceInstance(eq(StorageOperationStatus.OK), eq(true)))
1442             .thenReturn(ActionStatus.GENERAL_ERROR);
1443         when(toscaOperationFacade.dissociateResourceInstances(componentId, ref)).thenReturn(resultEither);
1444
1445         try {
1446             result = componentInstanceBusinessLogic
1447                 .batchDissociateRIFromRI(componentId, USER_ID, requirementDefList, componentTypeEnum);
1448             assertNotNull(result);
1449             assertEquals(new ArrayList<>(), result);
1450         } catch (ComponentException e) {
1451             assertEquals(e.getActionStatus().toString(), StorageOperationStatus.GENERAL_ERROR.toString());
1452         }
1453
1454         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1455         service.setLifecycleState(oldLifeCycleState);
1456
1457     }
1458
1459     @Test
1460     void testDissociateRIFromRISuccess() {
1461
1462         List<RequirementCapabilityRelDef> result;
1463         RequirementCapabilityRelDef ref = new RequirementCapabilityRelDef();
1464         List<RequirementCapabilityRelDef> requirementDefList = new ArrayList<>();
1465         requirementDefList.add(ref);
1466         ComponentTypeEnum componentTypeEnum = service.getComponentType();
1467         String componentId = service.getUniqueId();
1468         LifecycleStateEnum oldLifeCycleState = service.getLifecycleState();
1469         String oldLastUpdatedUserId = service.getLastUpdaterUserId();
1470         service.setLastUpdaterUserId(USER_ID);
1471         service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1472
1473         Either<Component, StorageOperationStatus> cont = Either.left(service);
1474         when(toscaOperationFacade.getToscaElement(eq(service.getUniqueId()), any(ComponentParametersView.class)))
1475             .thenReturn(cont);
1476         when(graphLockOperation.unlockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1477             .thenReturn(StorageOperationStatus.OK);
1478         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Service)))
1479             .thenReturn(StorageOperationStatus.OK);
1480         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultEither;
1481         resultEither = Either.left(ref);
1482         when(toscaOperationFacade.dissociateResourceInstances(componentId, ref)).thenReturn(resultEither);
1483
1484         result = componentInstanceBusinessLogic
1485             .batchDissociateRIFromRI(componentId, USER_ID, requirementDefList, componentTypeEnum);
1486         assertNotNull(result);
1487
1488         service.setLastUpdaterUserId(oldLastUpdatedUserId);
1489         service.setLifecycleState(oldLifeCycleState);
1490
1491         assertEquals(requirementDefList, result);
1492     }
1493
1494     @Test
1495     void testGetComponentInstancePropertyByPolicyId_success() {
1496         Optional<ComponentInstanceProperty> propertyCandidate =
1497             getComponentInstanceProperty(PROP_NAME);
1498
1499         assertThat(propertyCandidate.isPresent()).isTrue();
1500         assertEquals(propertyCandidate.get().getName(), PROP_NAME);
1501     }
1502
1503     @Test
1504     void testGetComponentInstancePropertyByPolicyId_failure() {
1505         Optional<ComponentInstanceProperty> propertyCandidate =
1506             getComponentInstanceProperty(NON_EXIST_NAME);
1507
1508         assertEquals(propertyCandidate, Optional.empty());
1509     }
1510
1511     private Optional<ComponentInstanceProperty> getComponentInstanceProperty(String propertyName) {
1512         ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
1513         componentInstanceProperty.setName(propertyName);
1514
1515         PolicyDefinition policyDefinition = getPolicyDefinition();
1516         componentInstanceProperty.setGetPolicyValues(policyDefinition.getGetPolicyValues());
1517
1518         service.setComponentInstancesProperties(
1519             Collections.singletonMap(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceProperty)));
1520
1521         return componentInstanceBusinessLogic.getComponentInstancePropertyByPolicyId(service, policyDefinition);
1522     }
1523
1524     private PolicyDefinition getPolicyDefinition() {
1525         PolicyDefinition policyDefinition = new PolicyDefinition();
1526         policyDefinition.setInstanceUniqueId(COMPONENT_INSTANCE_ID);
1527         policyDefinition.setName(PROP_NAME);
1528
1529         GetPolicyValueDataDefinition getPolicy = new GetPolicyValueDataDefinition();
1530         getPolicy.setPropertyName(PROP_NAME);
1531
1532         List<GetPolicyValueDataDefinition> getPolicies = new ArrayList<>();
1533         getPolicies.add(getPolicy);
1534         policyDefinition.setGetPolicyValues(getPolicies);
1535
1536         return policyDefinition;
1537     }
1538
1539     private ComponentInstance createComponetInstanceFromComponent(Component component) {
1540         ComponentInstance componentInst = new ComponentInstance();
1541         componentInst.setUniqueId(component.getUniqueId());
1542         componentInst.setComponentUid(component.getUniqueId() + "_test");
1543         componentInst.setPosX("10");
1544         componentInst.setPosY("10");
1545         componentInst.setCapabilities(component.getCapabilities());
1546         componentInst.setRequirements(component.getRequirements());
1547         componentInst.setArtifacts(component.getArtifacts());
1548         componentInst.setDeploymentArtifacts(component.getDeploymentArtifacts());
1549         return componentInst;
1550     }
1551
1552     // Prepare ComponentInstance & Resource objects used in createComponentInstance() tests
1553     private Pair<ComponentInstance, Resource> prepareResourcesForCreateComponentInstanceTest() {
1554         ComponentInstance instanceToBeCreated = new ComponentInstance();
1555         instanceToBeCreated.setName(COMPONENT_INSTANCE_NAME);
1556         instanceToBeCreated.setUniqueId(COMPONENT_INSTANCE_ID);
1557         instanceToBeCreated.setComponentUid(ORIGIN_COMPONENT_ID);
1558         instanceToBeCreated.setOriginType(OriginTypeEnum.VF);
1559
1560         Resource originComponent = new Resource();
1561         originComponent.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1562         originComponent.setResourceType(ResourceTypeEnum.VF);
1563         originComponent.setVersion(ORIGIN_COMPONENT_VERSION);
1564         originComponent.setIcon(ICON_NAME);
1565
1566         return Pair.of(instanceToBeCreated, originComponent);
1567     }
1568
1569     // Common part for testing component instance name validation
1570     private void testCreateComponentInstanceNameValidationFailure(String ciName) {
1571         ComponentInstance ci = new ComponentInstance();
1572         ci.setName(ciName);
1573
1574         // Stub for getting component
1575         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1576             .thenReturn(Either.left(service));
1577
1578         // Expecting ByActionStatusComponentException
1579         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1580             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1581         });
1582         assertEquals(ActionStatus.INVALID_COMPONENT_NAME, e.getActionStatus());
1583     }
1584
1585     @TestFactory
1586     Iterable<DynamicTest> testCreateComponentInstanceNameValidationFailureFactory() {
1587         String longName = String.join("", Collections.nCopies(ValidationUtils.COMPONENT_NAME_MAX_LENGTH + 1, "x"));
1588         String invalidName = "componentInstance#name";
1589         return Arrays.asList(
1590             dynamicTest("instance name is empty", () ->
1591                 testCreateComponentInstanceNameValidationFailure("")),
1592             dynamicTest("instance name is too long", () ->
1593                 testCreateComponentInstanceNameValidationFailure(longName)),
1594             dynamicTest("instance name includes invalid character", () ->
1595                 testCreateComponentInstanceNameValidationFailure(invalidName))
1596         );
1597     }
1598
1599     @Test
1600     void testCreateComponentInstanceFailToGetComponent() {
1601         ComponentInstance ci = prepareResourcesForCreateComponentInstanceTest().getLeft();
1602
1603         // Stub for getting component
1604         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1605             .thenReturn(Either.left(service));
1606         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1607             .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1608         when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE))
1609             .thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
1610
1611         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1612             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1613         });
1614         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
1615     }
1616
1617     @Test
1618     void testCreateComponentInstanceFailureInvalidState() {
1619         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1620         ComponentInstance ci = p.getLeft();
1621         Resource originComponent = p.getRight();
1622         originComponent.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1623
1624         // Stub for getting component
1625         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1626             .thenReturn(Either.left(service));
1627         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1628             .thenReturn(Either.left(originComponent));
1629
1630         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1631             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1632         });
1633         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE);
1634     }
1635
1636     @Test
1637     void testCreateComponentInstanceFailureArchived() {
1638         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1639         ComponentInstance ci = p.getLeft();
1640         Resource originComponent = p.getRight();
1641         originComponent.setArchived(Boolean.TRUE);
1642
1643         // Stub for getting component
1644         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1645             .thenReturn(Either.left(service));
1646         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1647             .thenReturn(Either.left(originComponent));
1648
1649         ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1650             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1651         });
1652         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.COMPONENT_IS_ARCHIVED);
1653     }
1654
1655     @Test
1656     void testCreateComponentInstanceFailureInvalidOriginType() {
1657         Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1658         ComponentInstance ci = p.getLeft();
1659         Resource originComponent = p.getRight();
1660         ci.setOriginType(OriginTypeEnum.VFC); // Set different type from origin
1661
1662         // Stub for getting component
1663         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1664             .thenReturn(Either.left(service));
1665         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1666             .thenReturn(Either.left(originComponent));
1667
1668         final ByActionStatusComponentException e = assertThrows(ByActionStatusComponentException.class, () -> {
1669             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1670         });
1671         assertThat(e.getActionStatus()).isEqualTo(ActionStatus.INVALID_CONTENT);
1672     }
1673
1674     @Test
1675     void testCreateComponentInstanceFailureCannotContainInstance() {
1676         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1677         final ComponentInstance ci = p.getLeft();
1678         final Resource originComponent = p.getRight();
1679
1680         // Stub for getting component
1681         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1682             .thenReturn(Either.left(service));
1683         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1684             .thenReturn(Either.left(originComponent));
1685         // Assume services cannot contain VF resource
1686         when(containerInstanceTypeData.isAllowedForServiceComponent(eq(ResourceTypeEnum.VF)))
1687             .thenReturn(false);
1688
1689         ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class, () -> {
1690             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1691         });
1692         assertThat(actualException.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE);
1693         verify(containerInstanceTypeData, times(1)).isAllowedForServiceComponent(eq(ResourceTypeEnum.VF));
1694
1695         //given
1696         final Resource resource = createResource();
1697         resource.setResourceType(ResourceTypeEnum.VF);
1698         resource.setLastUpdaterUserId(USER_ID);
1699         //when
1700         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1701             .thenReturn(Either.left(resource));
1702         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1703             .thenReturn(Either.left(originComponent));
1704         when(containerInstanceTypeData.isAllowedForResourceComponent(eq(ResourceTypeEnum.VF), eq(ResourceTypeEnum.VF)))
1705             .thenReturn(false);
1706         actualException = assertThrows(ByActionStatusComponentException.class, () -> {
1707             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1708         });
1709         //then
1710         assertThat(actualException.getActionStatus()).isEqualTo(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE);
1711     }
1712
1713     @Test
1714     void testCreateComponentInstanceFailureAddToGraph() {
1715         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1716         final ComponentInstance ci = p.getLeft();
1717         final Resource originComponent = p.getRight();
1718
1719         // TODO Refactor createComponentInstance() method and reduce these mocks
1720         //      not to target the internal details too much
1721         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1722             .thenReturn(Either.left(service));
1723         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1724             .thenReturn(Either.left(originComponent));
1725         when(containerInstanceTypeData.isAllowedForServiceComponent(eq(ResourceTypeEnum.VF)))
1726             .thenReturn(true);
1727         Mockito.doNothing().when(compositionBusinessLogic).validateAndSetDefaultCoordinates(ci);
1728         when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1729             .thenReturn(StorageOperationStatus.OK);
1730         when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(service, originComponent, ci, false, user))
1731             .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST));
1732         when(componentsUtils.convertFromStorageResponseForResourceInstance(StorageOperationStatus.BAD_REQUEST, true))
1733             .thenReturn(ActionStatus.INVALID_CONTENT);
1734         when(componentsUtils.getResponseFormatForResourceInstance(ActionStatus.INVALID_CONTENT, "", null))
1735             .thenReturn(new ResponseFormat());
1736         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
1737         when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1738             .thenReturn(StorageOperationStatus.OK);
1739
1740         assertThrows(ByResponseFormatComponentException.class, () -> {
1741             componentInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, ci);
1742         });
1743         verify(containerInstanceTypeData, times(1))
1744             .isAllowedForServiceComponent(eq(ResourceTypeEnum.VF));
1745         verify(compositionBusinessLogic, times(1)).validateAndSetDefaultCoordinates(ci);
1746         verify(toscaOperationFacade, times(1))
1747             .addComponentInstanceToTopologyTemplate(service, originComponent, ci, false, user);
1748         verify(graphLockOperation, times(1)).unlockComponent(COMPONENT_ID, NodeTypeEnum.Service);
1749     }
1750
1751     @Test
1752     void testCreateComponentInstanceSuccess() {
1753         final Pair<ComponentInstance, Resource> p = prepareResourcesForCreateComponentInstanceTest();
1754         final ComponentInstance instanceToBeCreated = p.getLeft();
1755         final Resource originComponent = p.getRight();
1756
1757         final Service updatedService = new Service();
1758         updatedService.setComponentInstances(Collections.singletonList(instanceToBeCreated));
1759         updatedService.setUniqueId(service.getUniqueId());
1760
1761         // TODO Refactor createComponentInstance() method and reduce these mocks
1762         //      not to target the internal details too much
1763         when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class)))
1764             .thenReturn(Either.left(service));
1765         when(toscaOperationFacade.getToscaFullElement(eq(ORIGIN_COMPONENT_ID)))
1766             .thenReturn(Either.left(originComponent));
1767         when(containerInstanceTypeData.isAllowedForServiceComponent(eq(ResourceTypeEnum.VF)))
1768             .thenReturn(true);
1769         Mockito.doNothing().when(compositionBusinessLogic).validateAndSetDefaultCoordinates(instanceToBeCreated);
1770         when(graphLockOperation.lockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1771             .thenReturn(StorageOperationStatus.OK);
1772         when(toscaOperationFacade.addComponentInstanceToTopologyTemplate(service, originComponent, instanceToBeCreated, false, user))
1773             .thenReturn(Either.left(new ImmutablePair<>(updatedService, COMPONENT_INSTANCE_ID)));
1774         when(artifactsBusinessLogic.getArtifacts(
1775             ORIGIN_COMPONENT_ID, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null))
1776             .thenReturn(Either.left(new HashMap<>()));
1777         when(toscaOperationFacade
1778             .addInformationalArtifactsToInstance(service.getUniqueId(), instanceToBeCreated, originComponent.getArtifacts()))
1779             .thenReturn(StorageOperationStatus.OK);
1780         when(janusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
1781         when(graphLockOperation.unlockComponent(COMPONENT_ID, NodeTypeEnum.Service))
1782             .thenReturn(StorageOperationStatus.OK);
1783
1784         final ComponentInstance result = componentInstanceBusinessLogic.createComponentInstance(
1785             ComponentTypeEnum.SERVICE_PARAM_NAME, COMPONENT_ID, USER_ID, instanceToBeCreated);
1786         assertThat(result).isEqualTo(instanceToBeCreated);
1787         assertThat(instanceToBeCreated.getComponentVersion()).isEqualTo(originComponent.getVersion());
1788         assertThat(instanceToBeCreated.getIcon()).isEqualTo(originComponent.getIcon());
1789         verify(containerInstanceTypeData, times(1))
1790             .isAllowedForServiceComponent(eq(ResourceTypeEnum.VF));
1791         verify(compositionBusinessLogic, times(1)).validateAndSetDefaultCoordinates(instanceToBeCreated);
1792         verify(toscaOperationFacade, times(1))
1793             .addComponentInstanceToTopologyTemplate(service, originComponent, instanceToBeCreated, false, user);
1794         // Check graph db change was committed
1795         verify(janusGraphDao, times(1)).commit();
1796     }
1797 }