8aa4353266c61484bacd4cffd5f7bc9e67d18eee
[sdc.git] / catalog-model / src / test / java / org / openecomp / sdc / be / model / jsonjanusgraph / operations / ToscaOperationFacadeTest.java
1 /*
2  * Copyright (c) 2018 AT&T Intellectual Property.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
17
18 import static org.assertj.core.api.Assertions.assertThat;
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertNotNull;
22 import static org.junit.jupiter.api.Assertions.assertNull;
23 import static org.junit.jupiter.api.Assertions.assertSame;
24 import static org.junit.jupiter.api.Assertions.assertThrows;
25 import static org.junit.jupiter.api.Assertions.assertTrue;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.ArgumentMatchers.anyInt;
28 import static org.mockito.ArgumentMatchers.anyMap;
29 import static org.mockito.ArgumentMatchers.anyString;
30 import static org.mockito.ArgumentMatchers.eq;
31 import static org.mockito.Mockito.doReturn;
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.EnumMap;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.stream.Collectors;
47 import java.util.stream.IntStream;
48 import org.apache.commons.collections.map.HashedMap;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.junit.jupiter.api.BeforeEach;
51 import org.junit.jupiter.api.Test;
52 import org.junit.jupiter.api.extension.ExtendWith;
53 import org.mockito.ArgumentCaptor;
54 import org.mockito.ArgumentMatchers;
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.config.ComponentType;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.dao.api.exception.JanusGraphException;
63 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphDao;
64 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
65 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
66 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
67 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
68 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
69 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
74 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
75 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
76 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
77 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
79 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
80 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
81 import org.openecomp.sdc.be.model.AttributeDefinition;
82 import org.openecomp.sdc.be.model.Component;
83 import org.openecomp.sdc.be.model.ComponentInstance;
84 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
85 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
86 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
87 import org.openecomp.sdc.be.model.ComponentParametersView;
88 import org.openecomp.sdc.be.model.DataTypeDefinition;
89 import org.openecomp.sdc.be.model.InputDefinition;
90 import org.openecomp.sdc.be.model.LifecycleStateEnum;
91 import org.openecomp.sdc.be.model.OutputDefinition;
92 import org.openecomp.sdc.be.model.PolicyDefinition;
93 import org.openecomp.sdc.be.model.PropertyDefinition;
94 import org.openecomp.sdc.be.model.Resource;
95 import org.openecomp.sdc.be.model.Service;
96 import org.openecomp.sdc.be.model.User;
97 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType;
98 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
99 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
100 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
101 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
102 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
103 import org.openecomp.sdc.be.model.operations.StorageException;
104 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
105 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
106
107 @ExtendWith(MockitoExtension.class)
108 class ToscaOperationFacadeTest {
109
110     private static final String COMPONENT_ID = "componentId";
111     private static final String PROPERTY1_NAME = "prop1";
112     private static final String PROPERTY1_TYPE = "string";
113     private static final String PROPERTY2_NAME = "prop2";
114     private static final String PROPERTY2_TYPE = "integer";
115     private static final String ICON_NAME = "icon";
116     private static final String SERVICE_MODEL_NAME = "Test_Service";
117     private static final String SERVICE_PROXY_INSTANCE0_NAME = "testservice_proxy0";
118     private static final String SERVICE_SUBSTITUTION_INSTANCE0_NAME = "testservice0";
119
120     @InjectMocks
121     private ToscaOperationFacade testInstance;
122
123     @Mock
124     private HealingJanusGraphDao janusGraphDaoMock;
125
126     @Mock
127     private TopologyTemplateOperation topologyTemplateOperationMock;
128
129     @Mock
130     private NodeTypeOperation nodeTypeOperationMock;
131
132     @Mock
133     private NodeTemplateOperation nodeTemplateOperationMock;
134
135     @Mock
136     private IGraphLockOperation graphLockOperationMock;
137
138     @BeforeEach
139     void setUp() throws Exception {
140         testInstance = new ToscaOperationFacade();
141         MockitoAnnotations.openMocks(this);
142     }
143
144     @SuppressWarnings("unchecked")
145     @Test
146     void fetchMetaDataByResourceType() throws Exception {
147         ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class);
148         ArgumentCaptor<Map> criteriaNotCapture = ArgumentCaptor.forClass(Map.class);
149         ComponentParametersView dataFilter = new ComponentParametersView();
150         List<GraphVertex> mockVertices = getMockVertices(2);
151         Either<List<GraphVertex>, JanusGraphOperationStatus> returnedVertices = Either.left(mockVertices);
152
153         when(janusGraphDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata)))
154             .thenReturn(returnedVertices);
155         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0")));
156         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1")));
157         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance
158             .fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter);
159
160         verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture);
161         verifyCriteriaNotIsDeleted(criteriaNotCapture);
162
163         assertTrue(fetchedComponents.isLeft());
164         List<Component> cmpts = fetchedComponents.left().value();
165         assertEquals(2, cmpts.size());
166         assertEquals("0", cmpts.get(0).getUniqueId());
167         assertEquals("1", cmpts.get(1).getUniqueId());
168     }
169
170     private void verifyCriteriaForHighestVersionAndVfResourceType(ArgumentCaptor<Map> criteriaCapture) {
171         Map<GraphPropertyEnum, Object> criteria = (Map<GraphPropertyEnum, Object>) criteriaCapture.getValue();
172         assertEquals(2, criteria.size());
173         assertEquals("VF", criteria.get(GraphPropertyEnum.RESOURCE_TYPE));
174         assertEquals(true, criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION));
175     }
176
177     private void verifyCriteriaNotIsDeleted(ArgumentCaptor<Map> criteriaNotCapture) {
178         Map<GraphPropertyEnum, Object> notCriteria = (Map<GraphPropertyEnum, Object>) criteriaNotCapture.getValue();
179         assertEquals(1, notCriteria.size());
180         assertEquals(true, notCriteria.get(GraphPropertyEnum.IS_DELETED));
181     }
182
183     @SuppressWarnings("unchecked")
184     @Test
185     void fetchMetaDataByResourceType_failedToGetData() throws Exception {
186         when(janusGraphDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(
187             JanusGraphOperationStatus.GENERAL_ERROR));
188         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance
189             .fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView());
190         assertTrue(fetchedComponents.isRight());
191         assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value());
192     }
193
194     @Test
195     void associatePolicyToComponentSuccessTest() {
196         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK);
197         assertTrue(result.isLeft());
198     }
199
200     @Test
201     void associatePolicyToComponentFailureTest() {
202         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
203         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
204     }
205
206     @Test
207     void updatePolicyOfComponentSuccessTest() {
208         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK);
209         assertTrue(result.isLeft());
210     }
211
212     @Test
213     void updatePolicyOfComponentFailureTest() {
214         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND);
215         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
216     }
217
218     @Test
219     void removePolicyFromComponentSuccessTest() {
220         removePolicyFromComponentWithStatus(StorageOperationStatus.OK);
221     }
222
223     @Test
224     void removePolicyFromComponentFailureTest() {
225         removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND);
226     }
227
228     @Test
229     void testFindLastCertifiedToscaElementByUUID() {
230         Either<Component, StorageOperationStatus> result;
231         Component component = new Resource();
232         List<GraphVertex> list = new ArrayList<>();
233         GraphVertex graphVertex = getTopologyTemplateVertex();
234         list.add(graphVertex);
235         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
236         props.put(GraphPropertyEnum.UUID, component.getUUID());
237         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
238         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
239         ToscaElement toscaElement = getToscaElementForTest();
240         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class)))
241             .thenReturn(Either.left(toscaElement));
242         when(janusGraphDaoMock.getByCriteria(ModelConverter.getVertexType(component), props)).thenReturn(Either.left(list));
243         result = testInstance.findLastCertifiedToscaElementByUUID(component);
244         Component resultComp = result.left().value();
245         assertEquals(resultComp.getToscaType(), ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
246     }
247
248     @Test
249     void testLatestComponentByToscaResourceName() {
250         Either<Component, StorageOperationStatus> result;
251         TopologyTemplate toscaElement = new TopologyTemplate();
252         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
253         List<GraphVertex> list = new ArrayList<>();
254         GraphVertex graphVertex = getTopologyTemplateVertex();
255         Map<GraphPropertyEnum, Object> props = new HashMap<>();
256         props.put(GraphPropertyEnum.VERSION, "1.0");
257         graphVertex.setMetadataProperties(props);
258         list.add(graphVertex);
259
260         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
261         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
262         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "toscaResourceName");
263         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
264         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
265
266         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, null))
267             .thenReturn(Either.left(list));
268         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class)))
269             .thenReturn(Either.left(toscaElement));
270
271         result = testInstance.getFullLatestComponentByToscaResourceName("toscaResourceName");
272         assertTrue(result.isLeft());
273     }
274
275     @Test
276     void testValidateCsarUuidUniqueness() {
277         StorageOperationStatus result;
278         String csarUUID = "csarUUID";
279         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
280         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
281         List<GraphVertex> vertexList = new ArrayList<>();
282         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
283         result = testInstance.validateCsarUuidUniqueness(csarUUID);
284         assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, result);
285     }
286
287     @Test
288     void testValidateCsarUuidUnique_true() {
289         StorageOperationStatus result;
290         String csarUUID = "csarUUID";
291         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
292         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
293         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
294             JanusGraphOperationStatus.NOT_FOUND));
295         result = testInstance.validateCsarUuidUniqueness(csarUUID);
296         assertEquals(StorageOperationStatus.OK, result);
297     }
298
299     @Test
300     void testGetLatestCertiNodeTypeByToscaResourceName() {
301         Either<Resource, StorageOperationStatus> result;
302         String toscaResourceName = "resourceName";
303         String uniqueId = "uniqueId";
304         GraphVertex graphVertex = getTopologyTemplateVertex();
305         graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "1.0");
306         graphVertex.setUniqueId(uniqueId);
307         List<GraphVertex> vertexList = new ArrayList<>();
308         vertexList.add(graphVertex);
309         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
310         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
311         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
312         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
313         ToscaElement topologyTemplate = new TopologyTemplate();
314         topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE);
315         when(janusGraphDaoMock.getByCriteria(VertexTypeEnum.NODE_TYPE, props, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
316         when(janusGraphDaoMock.getVertexById(uniqueId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
317         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
318             .thenReturn(Either.left(topologyTemplate));
319         result = testInstance.getLatestCertifiedNodeTypeByToscaResourceName(toscaResourceName);
320         assertTrue(result.isLeft());
321     }
322
323     @Test
324     void testValidateCompExists() {
325         Either<Boolean, StorageOperationStatus> result;
326         String componentId = "componentId";
327         GraphVertex graphVertex = getTopologyTemplateVertex();
328         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
329         result = testInstance.validateComponentExists(componentId);
330         assertEquals(true, result.left().value());
331     }
332
333     @Test
334     void testValidateCompExists_NotFound() {
335         Either<Boolean, StorageOperationStatus> result;
336         String componentId = "componentId";
337         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
338             JanusGraphOperationStatus.NOT_FOUND));
339         result = testInstance.validateComponentExists(componentId);
340         assertEquals(false, result.left().value());
341     }
342
343     @Test
344     void testValidateToscaResourceNameExists() {
345         Either<Boolean, StorageOperationStatus> result;
346         String templateName = "templateName";
347         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
348         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
349         List<GraphVertex> graphVertexList = new ArrayList<>();
350         GraphVertex graphVertex = getTopologyTemplateVertex();
351         graphVertexList.add(graphVertex);
352         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList));
353         result = testInstance.validateToscaResourceNameExists(templateName);
354         assertEquals(true, result.left().value());
355     }
356
357     @Test
358     void testValidateToscaResourceNameExists_false() {
359         Either<Boolean, StorageOperationStatus> result;
360         String templateName = "templateName";
361         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
362         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
363         List<GraphVertex> graphVertexList = new ArrayList<>();
364         GraphVertex graphVertex = getTopologyTemplateVertex();
365         graphVertexList.add(graphVertex);
366         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
367             JanusGraphOperationStatus.NOT_FOUND));
368         result = testInstance.validateToscaResourceNameExists(templateName);
369         assertEquals(false, result.left().value());
370     }
371
372     @Test
373     void testOverrideComponent() {
374         Either<Resource, StorageOperationStatus> result;
375         Resource resource = new Resource();
376         String id = "id";
377         resource.setUniqueId(id);
378         GraphVertex graphVertex = getTopologyTemplateVertex();
379         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
380         NodeType nodeType = new NodeType();
381         nodeType.setComponentType(ComponentTypeEnum.RESOURCE);
382         ToscaElement toscaElement = new TopologyTemplate();
383         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
384         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
385         when(janusGraphDaoMock.getParentVertex(graphVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
386         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
387         when(nodeTypeOperationMock.createToscaElement(any(ToscaElement.class))).thenReturn(Either.left(nodeType));
388         when(janusGraphDaoMock.getVertexById(null, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
389         when(janusGraphDaoMock.createEdge(graphVertex, graphVertex, EdgeLabelEnum.VERSION, null)).thenReturn(
390             JanusGraphOperationStatus.OK);
391         result = testInstance.overrideComponent(resource, resource);
392         assertTrue(result.isLeft());
393     }
394
395     @Test
396     void testGetToscaElement() {
397         Either<Component, StorageOperationStatus> result;
398         String id = "id";
399         GraphVertex graphVertex = getTopologyTemplateVertex();
400         ToscaElement toscaElement = getToscaElementForTest();
401         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
402         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
403             .thenReturn(Either.left(toscaElement));
404         result = testInstance.getToscaElement(id, JsonParseFlagEnum.ParseAll);
405         assertTrue(result.isLeft());
406     }
407
408     @Test
409     void testDeleteService_ServiceInUse() {
410         String invariantUUID = "12345";
411         String serviceUid = "1";
412         GraphVertex service1 = getTopologyTemplateVertex();
413         service1.setUniqueId(serviceUid);
414         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
415         allResourcesToDelete.add(service1);
416         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
417         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, invariantUUID);
418         ToscaElement toscaElement = getToscaElementForTest();
419         toscaElement.setUniqueId(serviceUid);
420         String service2Name = "service2Name";
421         Map<String, Object> service2MetadataJson = new HashMap<>();
422         service2MetadataJson.put(GraphPropertyEnum.COMPONENT_TYPE.getProperty(), ComponentType.SERVICE);
423         service2MetadataJson.put(GraphPropertyEnum.NAME.getProperty(), service2Name);
424         String service2Uid = "2";
425         GraphVertex usingService = getTopologyTemplateVertex();
426         usingService.setUniqueId(service2Uid);
427         usingService.setMetadataJson(service2MetadataJson);
428         List<GraphVertex> inUseBy = new ArrayList<>();
429         inUseBy.add(usingService);
430
431         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
432             thenReturn(allResourcesToDelete);
433         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), eq(JsonParseFlagEnum.ParseAll))).
434             thenReturn(Either.left(inUseBy)).thenReturn(Either.left(inUseBy));
435         final OperationException actualException = assertThrows(OperationException.class, () -> testInstance.deleteService(invariantUUID, true));
436         assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualException.getActionStatus());
437         assertEquals(actualException.getParams()[0], ComponentType.SERVICE + " " + service2Name);
438     }
439
440     @Test
441     void testDeleteService_WithOneVersion() {
442         String invariantUUID = "12345";
443         String serviceUid = "1";
444         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
445         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, invariantUUID);
446         GraphVertex service1 = getTopologyTemplateVertex();
447         service1.setUniqueId(serviceUid);
448         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
449         allResourcesToDelete.add(service1);
450         ToscaElement toscaElement = getToscaElementForTest();
451         toscaElement.setUniqueId(serviceUid);
452         List<String> affectedComponentIds = new ArrayList<>();
453         affectedComponentIds.add(service1.getUniqueId());
454
455         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
456             thenReturn(allResourcesToDelete);
457         when(janusGraphDaoMock.getParentVertices(eq(service1), any(), eq(JsonParseFlagEnum.ParseAll))).
458             thenReturn(Either.right(JanusGraphOperationStatus.OK));
459         when(graphLockOperationMock.lockComponent(service1.getUniqueId(), NodeTypeEnum.Service)).
460             thenReturn(StorageOperationStatus.OK);
461         when(topologyTemplateOperationMock.deleteToscaElement(service1)).thenReturn(Either.left(toscaElement));
462         assertEquals(affectedComponentIds, testInstance.deleteService(invariantUUID, true));
463     }
464
465     @Test
466     void testDeleteService_WithTwoVersions() {
467         String invariantUUID = "12345";
468         String serviceUid = "1";
469         String service2Uid = "2";
470         GraphVertex service = getTopologyTemplateVertex();
471         service.setUniqueId(serviceUid);
472         GraphVertex serviceV2 = getTopologyTemplateVertex();
473         serviceV2.setUniqueId(service2Uid);
474         ToscaElement toscaElement = getToscaElementForTest();
475         toscaElement.setUniqueId(serviceUid);
476         ToscaElement toscaElement2 = getToscaElementForTest();
477         toscaElement2.setUniqueId(service2Uid);
478         List<String> affectedComponentIds = new ArrayList<>();
479         affectedComponentIds.add(service.getUniqueId());
480         affectedComponentIds.add(serviceV2.getUniqueId());
481         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
482         allResourcesToDelete.add(service);
483         allResourcesToDelete.add(serviceV2);
484         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
485         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, invariantUUID);
486
487         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
488             thenReturn(allResourcesToDelete);
489         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), eq(JsonParseFlagEnum.ParseAll))).
490             thenReturn(Either.right(JanusGraphOperationStatus.OK));
491         when(graphLockOperationMock.lockComponent(service.getUniqueId(), NodeTypeEnum.Service)).
492             thenReturn(StorageOperationStatus.OK);
493         when(graphLockOperationMock.lockComponent(serviceV2.getUniqueId(), NodeTypeEnum.Service)).
494             thenReturn(StorageOperationStatus.OK);
495         when(topologyTemplateOperationMock.deleteToscaElement(service)).thenReturn(Either.left(toscaElement));
496         when(topologyTemplateOperationMock.deleteToscaElement(serviceV2)).thenReturn(Either.left(toscaElement));
497         assertEquals(affectedComponentIds, testInstance.deleteService(invariantUUID, true));
498     }
499
500     @Test
501     void testDeleteService_FailDelete() {
502         String invariantUUID = "12345";
503         String serviceUid = "1";
504         GraphVertex service = getTopologyTemplateVertex();
505         service.setUniqueId(serviceUid);
506         ToscaElement toscaElement = getToscaElementForTest();
507         toscaElement.setUniqueId(serviceUid);
508         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
509         allResourcesToDelete.add(service);
510
511         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
512             thenReturn(allResourcesToDelete);
513         when(janusGraphDaoMock.getParentVertices(eq(service), any(), eq(JsonParseFlagEnum.ParseAll))).
514             thenReturn(Either.right(JanusGraphOperationStatus.OK));
515         when(graphLockOperationMock.lockComponent(service.getUniqueId(), NodeTypeEnum.Service)).
516             thenReturn(StorageOperationStatus.OK);
517         when(topologyTemplateOperationMock.deleteToscaElement(service))
518             .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
519         StorageException actualException = assertThrows(StorageException.class, () -> testInstance.deleteService(invariantUUID, false));
520         assertEquals(StorageOperationStatus.NOT_FOUND, actualException.getStorageOperationStatus());
521         assertEquals(0, actualException.getParams().length);
522     }
523
524     @Test
525     void testDeleteService_NotFound() {
526         String invariantUUID = "12345";
527         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
528             thenReturn(Collections.emptyList());
529         assertEquals(0, testInstance.deleteService(invariantUUID, true).size());
530     }
531
532     @Test
533     void testDeleteService_GeneralErrorInJanusGraphDao() {
534         String invariantUUID = "12345";
535         JanusGraphException janusException = new JanusGraphException(JanusGraphOperationStatus.GENERAL_ERROR, "General error");
536         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).
537             thenThrow(janusException);
538
539         StorageException actualException = assertThrows(StorageException.class, () -> testInstance.deleteService(invariantUUID, false));
540         assertEquals(StorageOperationStatus.GENERAL_ERROR, actualException.getStorageOperationStatus());
541         assertEquals(0, actualException.getParams().length);
542     }
543
544     @Test
545     void testMarkComponentToDelete() {
546         StorageOperationStatus result;
547         Component component = new Resource();
548         String id = "id";
549         component.setUniqueId(id);
550         GraphVertex graphVertex = getTopologyTemplateVertex();
551         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
552         when(nodeTypeOperationMock.markComponentToDelete(graphVertex)).thenReturn(Either.left(graphVertex));
553         result = testInstance.markComponentToDelete(component);
554         assertEquals(StorageOperationStatus.OK, result);
555     }
556
557     @Test
558     void testDelToscaComponent() {
559         Either<Component, StorageOperationStatus> result;
560         String componentId = "compId";
561         GraphVertex graphVertex = getTopologyTemplateVertex();
562         ToscaElement toscaElement = getToscaElementForTest();
563         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
564         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
565         result = testInstance.deleteToscaComponent(componentId);
566         assertTrue(result.isLeft());
567     }
568
569     @Test
570     void testGetLatestByToscaResourceName() {
571         Either<Component, StorageOperationStatus> result;
572         String toscaResourceName = "name";
573         String model = "testModel";
574         ToscaElement toscaElement = getToscaElementForTest();
575
576         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
577         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
578         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
579         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
580         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
581
582         List<GraphVertex> graphVertexList = new ArrayList<>();
583         GraphVertex graphVertex = getTopologyTemplateVertex();
584         graphVertex.setUniqueId(toscaResourceName);
585         Map<GraphPropertyEnum, Object> props = new HashMap<>();
586         props.put(GraphPropertyEnum.VERSION, "1.0");
587         graphVertex.setMetadataProperties(props);
588         graphVertexList.add(graphVertex);
589
590         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata, model))
591             .thenReturn(Either.left(graphVertexList));
592         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
593             .thenReturn(Either.left(toscaElement));
594         result = testInstance.getLatestByToscaResourceName(toscaResourceName, model);
595         assertTrue(result.isLeft());
596     }
597
598
599     @Test
600     void testGetLatestResourceByToscaResourceName() {
601         Either<Resource, StorageOperationStatus> result;
602         String toscaResourceName = "org.openecomp.resource.vf";
603         ToscaElement toscaElement = getToscaElementForTest();
604
605         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
606         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
607         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
608         if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
609             propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
610         }
611
612         List<GraphVertex> graphVertexList = new ArrayList<>();
613         GraphVertex graphVertex = getTopologyTemplateVertex();
614         graphVertex.setUniqueId(toscaResourceName);
615         Map<JsonPresentationFields, Object> props = new HashMap<>();
616         props.put(JsonPresentationFields.VERSION, "1.0");
617         graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, props.get(JsonPresentationFields.VERSION));
618         graphVertexList.add(graphVertex);
619
620         when(janusGraphDaoMock.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata))
621             .thenReturn(Either.left(graphVertexList));
622         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
623             .thenReturn(Either.left(toscaElement));
624
625         when(janusGraphDaoMock.getVertexById(toscaResourceName, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
626
627         result = testInstance.getLatestResourceByToscaResourceName(toscaResourceName);
628         assertTrue(result.isLeft());
629     }
630
631     @Test
632     void testGetFollowed() {
633         Either<Set<Component>, StorageOperationStatus> result;
634         String userId = "id";
635         Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
636         Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
637         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
638         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
639         lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
640         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
641         List<ToscaElement> toscaEleList = new ArrayList<>();
642         ToscaElement toscaElement = getToscaElementForTest();
643         toscaEleList.add(toscaElement);
644         when(nodeTypeOperationMock.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType))
645             .thenReturn(Either.left(toscaEleList));
646         result = testInstance.getFollowed(userId, lifecycleStates, lastStateStates, componentType);
647         assertTrue(result.isLeft());
648         assertEquals(1, result.left().value().size());
649     }
650
651     @Test
652     void testGetBySystemName() {
653         Either<List<Component>, StorageOperationStatus> result;
654         String sysName = "sysName";
655         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
656         ToscaElement toscaElement = getToscaElementForTest();
657         List<GraphVertex> componentVertices = new ArrayList<>();
658         GraphVertex graphVertex = getTopologyTemplateVertex();
659         componentVertices.add(graphVertex);
660         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
661         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
662
663         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName);
664         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name());
665
666         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
667
668         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll))
669             .thenReturn(Either.left(componentVertices));
670         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
671             .thenReturn(Either.left(toscaElement));
672         result = testInstance.getBySystemName(componentTypeEnum, sysName);
673         assertTrue(result.isLeft());
674         assertEquals(1, result.left().value().size());
675     }
676
677     @Test
678     void testGetCompByNameAndVersion() {
679         Either<Component, StorageOperationStatus> result;
680         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
681         String name = "name";
682         String version = "1.0";
683         JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll;
684         List<GraphVertex> graphVertexList = new ArrayList<>();
685         GraphVertex graphVertex = getTopologyTemplateVertex();
686         graphVertexList.add(graphVertex);
687         ToscaElement toscaElement = getToscaElementForTest();
688         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
689         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
690
691         hasProperties.put(GraphPropertyEnum.NAME, name);
692         hasProperties.put(GraphPropertyEnum.VERSION, version);
693         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
694         hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
695         when(janusGraphDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList));
696         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
697             .thenReturn(Either.left(toscaElement));
698         result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag);
699         assertTrue(result.isLeft());
700     }
701
702     private ToscaElement getToscaElementForTest() {
703         ToscaElement toscaElement = new TopologyTemplate();
704         toscaElement.setComponentType(ComponentTypeEnum.RESOURCE);
705         return toscaElement;
706     }
707
708     @Test
709     void addDataTypesToComponentSuccessTest() {
710         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK);
711         assertTrue(result.isLeft());
712     }
713
714     @Test
715     void addDataTypesToComponentFailureTest_BadRequest() {
716         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
717         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
718     }
719
720     private Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) {
721         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
722         String componentId = "componentid";
723         String Id = "id";
724
725         PropertyDefinition noDefaultProp = new PropertyDefinition();
726         noDefaultProp.setName("noDefaultProp");
727         PropertyDefinition prop1 = new PropertyDefinition();
728         prop1.setDefaultValue("def1");
729         prop1.setName("prop1");
730         PropertyDefinition prop2 = new PropertyDefinition();
731         prop2.setType("dataType1");
732         prop2.setName("prop2");
733         PropertyDefinition prop3 = new PropertyDefinition();
734         prop3.setDefaultValue("def3");
735         prop3.setName("prop3");
736
737         DataTypeDefinition noDefaultValue = new DataTypeDefinition();
738         noDefaultValue.setProperties(Collections.singletonList(noDefaultProp));
739         noDefaultValue.setDerivedFromName("name0");
740
741         DataTypeDefinition dataType1 = new DataTypeDefinition();
742         dataType1.setProperties(Arrays.asList(prop1, prop3));
743         dataType1.setName("name1");
744         dataType1.setDerivedFromName("derivedfromname1");
745
746         DataTypeDefinition dataType2 = new DataTypeDefinition();
747         dataType2.setDerivedFrom(dataType1);
748         dataType2.setName("name2");
749         dataType2.setDerivedFromName("derivedfromname2");
750
751         DataTypeDefinition dataType3 = new DataTypeDefinition();
752         dataType3.setProperties(Collections.singletonList(prop2));
753         dataType3.setDerivedFrom(noDefaultValue);
754         dataType3.setName("name3");
755         dataType3.setDerivedFromName("derivedfromname3");
756
757         dataTypes.put("noDefault", noDefaultValue);
758         dataTypes.put("dataType1", dataType1);
759         dataTypes.put("dataType2", dataType2);
760         dataTypes.put("dataType3", dataType3);
761
762         GraphVertex vertex;
763         if (status == StorageOperationStatus.OK) {
764             vertex = getTopologyTemplateVertex();
765         } else {
766             vertex = getNodeTypeVertex();
767         }
768         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
769         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
770         when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex),
771             eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status);
772         return testInstance.addDataTypesToComponent(dataTypes, componentId);
773     }
774
775     @Test
776     void testDataTypesToComponentFailureTest_NotFound() {
777         Either<List<DataTypeDefinition>, StorageOperationStatus> result;
778         String componentId = "componentId";
779         GraphVertex vertex = getNodeTypeVertex();
780         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
781         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
782             JanusGraphOperationStatus.NOT_FOUND));
783         result = testInstance.addDataTypesToComponent(dataTypes, componentId);
784         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
785     }
786
787     @Test
788     void testDeleteDataTypeOfComponent() {
789         Component component = new Resource();
790         String id = "id";
791         component.setUniqueId(id);
792
793         DataTypeDefinition dataType1 = new DataTypeDefinition();
794         dataType1.setName("name1");
795         Map<String, DataTypeDataDefinition> dataTypeDataMap = new HashMap<>();
796         dataTypeDataMap.put("datatype1", dataType1);
797         List<DataTypeDefinition> dataTypeMap = dataTypeDataMap.values().stream().map(e -> {
798             return new DataTypeDefinition(e);
799         }).collect(Collectors.toList());
800         component.setDataTypes(dataTypeMap);
801         GraphVertex graphVertex = getTopologyTemplateVertex();
802         assertNull(testInstance.deleteDataTypeOfComponent(component, "datatype1"));
803     }
804
805     @Test
806     void testAddComponentInstancePropertiesToComponent() {
807         // set up component object
808         Component component = new Resource();
809         component.setUniqueId(COMPONENT_ID);
810         List<ComponentInstanceProperty> instanceProps = new ArrayList<>();
811         ComponentInstanceProperty instanceProp = new ComponentInstanceProperty();
812         instanceProp.setName(PROPERTY1_NAME);
813         instanceProp.setType(PROPERTY1_TYPE);
814         instanceProps.add(instanceProp);
815         instanceProp = new ComponentInstanceProperty();
816         instanceProp.setName(PROPERTY2_NAME);
817         instanceProp.setType(PROPERTY2_TYPE);
818         instanceProps.add(instanceProp);
819         Map<String, List<ComponentInstanceProperty>> instancePropsMap =
820             Collections.singletonMap(COMPONENT_ID, instanceProps);
821         component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>()));
822
823         when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any()))
824             .thenReturn(StorageOperationStatus.OK);
825
826         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> result =
827             testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap);
828         assertTrue(result.isLeft());
829         verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any());
830         List<ComponentInstanceProperty> resultProps = result.left().value().get(COMPONENT_ID);
831         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME)));
832         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME)));
833     }
834
835     @Test
836     void testAddComponentInstanceToTopologyTemplate_ServiceProxy() {
837         Component containerComponent = new Service();
838         Component originalComponent = new Service();
839         ComponentInstance componentInstance = new ComponentInstance();
840         ComponentInstance existingComponentInstance = new ComponentInstance();
841         User user = new User();
842
843         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
844
845         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
846         originalComponent.setIcon(ICON_NAME);
847
848         componentInstance.setOriginType(OriginTypeEnum.ServiceProxy);
849         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
850
851         List<ComponentInstance> existingInstances = new ArrayList<>();
852         existingComponentInstance.setNormalizedName(SERVICE_PROXY_INSTANCE0_NAME);
853         existingInstances.add(existingComponentInstance);
854         containerComponent.setComponentInstances(existingInstances);
855
856         when(nodeTemplateOperationMock
857             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
858             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
859         TopologyTemplate topologyTemplate = new TopologyTemplate();
860         // preset COMPONENT_TYPE field for internal ModelConverter call
861         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
862         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
863             .thenReturn(Either.left(topologyTemplate));
864
865         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
866             testInstance.addComponentInstanceToTopologyTemplate(
867                 containerComponent, originalComponent, componentInstance, false, user);
868
869         assertTrue(result.isLeft());
870         assertEquals(ICON_NAME, componentInstance.getIcon());
871         assertEquals(COMPONENT_ID, result.left().value().getRight());
872         // the instance counter must be 1 because the service proxy instance with suffix 0 already exists.
873         verify(nodeTemplateOperationMock, times(1))
874             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
875     }
876
877     @Test
878     void testAddComponentInstanceToTopologyTemplate_ServiceSubstitution() {
879         Component containerComponent = new Service();
880         Component originalComponent = new Service();
881         ComponentInstance componentInstance = new ComponentInstance();
882         ComponentInstance existingComponentInstance = new ComponentInstance();
883         User user = new User();
884
885         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
886
887         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
888         originalComponent.setIcon(ICON_NAME);
889
890         componentInstance.setOriginType(OriginTypeEnum.ServiceSubstitution);
891         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
892
893         List<ComponentInstance> existingInstances = new ArrayList<>();
894         existingComponentInstance.setNormalizedName(SERVICE_SUBSTITUTION_INSTANCE0_NAME);
895         existingInstances.add(existingComponentInstance);
896         containerComponent.setComponentInstances(existingInstances);
897
898         when(nodeTemplateOperationMock
899             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
900             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
901         TopologyTemplate topologyTemplate = new TopologyTemplate();
902         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
903         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
904             .thenReturn(Either.left(topologyTemplate));
905
906         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
907             testInstance.addComponentInstanceToTopologyTemplate(
908                 containerComponent, originalComponent, componentInstance, false, user);
909
910         assertTrue(result.isLeft());
911         assertEquals(ICON_NAME, componentInstance.getIcon());
912         assertEquals(COMPONENT_ID, result.left().value().getRight());
913         verify(nodeTemplateOperationMock, times(1))
914             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
915     }
916
917     @Test
918     void testUpdateComponentInstanceRequirement() {
919         String containerComponentId = "containerComponentId";
920         String componentInstanceUniqueId = "componentInstanceUniqueId";
921         RequirementDataDefinition requirementDataDefinition = Mockito.mock(RequirementDataDefinition.class);
922
923         when(nodeTemplateOperationMock.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition))
924             .thenReturn(StorageOperationStatus.OK);
925         StorageOperationStatus result = testInstance
926             .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
927         assertEquals(StorageOperationStatus.OK, result);
928         verify(nodeTemplateOperationMock, times(1))
929             .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
930
931     }
932
933     @Test
934     void associateCapabilitiesToServiceFailureTest() {
935         StorageOperationStatus result = associateCapabilitiesToServiceWithStatus(StorageOperationStatus.BAD_REQUEST);
936         assertSame(StorageOperationStatus.BAD_REQUEST, result);
937     }
938
939     @Test
940     void associateCapabilitiesToServiceSuccessTest() {
941         StorageOperationStatus result = associateCapabilitiesToServiceWithStatus(StorageOperationStatus.OK);
942         assertSame(StorageOperationStatus.OK, result);
943     }
944
945     private StorageOperationStatus associateCapabilitiesToServiceWithStatus(StorageOperationStatus status) {
946         Map<String, ListCapabilityDataDefinition> capabilitiesMap = new HashedMap();
947         String componentId = "componentid";
948
949         ListCapabilityDataDefinition listCapabilityDataDefinition1 = new ListCapabilityDataDefinition();
950         capabilitiesMap.put("capabilities1", listCapabilityDataDefinition1);
951
952         GraphVertex vertex;
953         if (status == StorageOperationStatus.OK) {
954             vertex = getTopologyTemplateVertex();
955         } else {
956             vertex = getNodeTypeVertex();
957         }
958
959         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
960         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
961         when(topologyTemplateOperationMock.associateElementToData(eq(vertex),
962             eq(VertexTypeEnum.CAPABILITIES), eq(EdgeLabelEnum.CAPABILITIES), anyMap())).thenReturn(Either.right(status));
963         return testInstance.associateCapabilitiesToService(capabilitiesMap, componentId);
964     }
965
966     @Test
967     void associateRequirementsToServiceFailureTest() {
968         StorageOperationStatus result = associateRequirementsToServiceWithStatus(StorageOperationStatus.BAD_REQUEST);
969         assertSame(StorageOperationStatus.BAD_REQUEST, result);
970     }
971
972     @Test
973     void associateRequirementsToServiceSuccessTest() {
974         StorageOperationStatus result = associateRequirementsToServiceWithStatus(StorageOperationStatus.OK);
975         assertSame(StorageOperationStatus.OK, result);
976     }
977
978     @Test
979     void test_addOutputsToComponent() {
980         final GraphVertex graphVertex = getTopologyTemplateVertex();
981
982         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse);
983         doReturn(StorageOperationStatus.OK).when(topologyTemplateOperationMock)
984             .addToscaDataToToscaElement(
985                 any(GraphVertex.class), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyMap(), eq(JsonPresentationFields.NAME));
986
987         final Map<String, OutputDefinition> outputs = new HashMap<>();
988         final OutputDefinition outputDefinition = new OutputDefinition();
989         outputs.put("mock", outputDefinition);
990         final Either<List<OutputDefinition>, StorageOperationStatus> result = testInstance.addOutputsToComponent(outputs, COMPONENT_ID);
991         assertNotNull(result);
992         assertTrue(result.isLeft());
993         assertFalse(result.left().value().isEmpty());
994         assertThat(result.left().value().get(0)).isInstanceOf(OutputDefinition.class);
995         verify(janusGraphDaoMock, times(1)).getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse);
996         verify(topologyTemplateOperationMock, times(1)).addToscaDataToToscaElement(
997             any(GraphVertex.class), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyMap(), eq(JsonPresentationFields.NAME));
998     }
999
1000     @Test
1001     void test_addComponentInstanceOutputsToComponent_updateComponentInstanceOutput() {
1002         final Component component = new Resource();
1003         component.setUniqueId(COMPONENT_ID);
1004         final Map<String, List<ComponentInstanceOutput>> map = new HashMap<>();
1005         final List<ComponentInstanceOutput> componentInstanceOutputList = new ArrayList<>();
1006         final ComponentInstanceOutput componentInstanceOutput = new ComponentInstanceOutput();
1007         componentInstanceOutput.setComponentInstanceId(COMPONENT_ID);
1008         componentInstanceOutput.setComponentInstanceName(COMPONENT_ID);
1009         componentInstanceOutput.setName(COMPONENT_ID);
1010         componentInstanceOutputList.add(componentInstanceOutput);
1011         map.put("mock", componentInstanceOutputList);
1012         component.setComponentInstancesOutputs(map);
1013
1014         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock)
1015             .updateComponentInstanceOutput(any(Component.class), anyString(), any(ComponentInstanceOutput.class));
1016
1017         final Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> result
1018             = testInstance.addComponentInstanceOutputsToComponent(component, map);
1019         assertNotNull(result);
1020         assertTrue(result.isLeft());
1021         assertFalse(result.left().value().isEmpty());
1022         assertSame(result.left().value(), map);
1023         verify(nodeTemplateOperationMock, times(1))
1024             .updateComponentInstanceOutput(any(Component.class), anyString(), any(ComponentInstanceOutput.class));
1025
1026     }
1027
1028     @Test
1029     void test_addComponentInstanceOutputsToComponent_addComponentInstanceOutput() {
1030         final Component component = new Resource();
1031         component.setUniqueId(COMPONENT_ID);
1032         Map<String, List<ComponentInstanceOutput>> map = new HashMap<>();
1033         List<ComponentInstanceOutput> componentInstanceOutputList = new ArrayList<>();
1034         ComponentInstanceOutput componentInstanceOutput = new ComponentInstanceOutput();
1035         componentInstanceOutput.setComponentInstanceId(COMPONENT_ID);
1036         componentInstanceOutput.setComponentInstanceName(COMPONENT_ID);
1037         componentInstanceOutput.setName(COMPONENT_ID);
1038         componentInstanceOutputList.add(componentInstanceOutput);
1039         map.put("mock", componentInstanceOutputList);
1040         component.setComponentInstancesOutputs(map);
1041
1042         map = new HashMap<>();
1043         componentInstanceOutputList = new ArrayList<>();
1044         componentInstanceOutput = new ComponentInstanceOutput();
1045         componentInstanceOutput.setComponentInstanceId("mock");
1046         componentInstanceOutput.setComponentInstanceName("mock");
1047         componentInstanceOutput.setName("mock");
1048         componentInstanceOutputList.add(componentInstanceOutput);
1049         map.put("mock", componentInstanceOutputList);
1050
1051         final Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> result = testInstance
1052             .addComponentInstanceOutputsToComponent(component, map);
1053         assertNotNull(result);
1054         assertTrue(result.isRight());
1055     }
1056
1057     @Test
1058     void test_addComponentInstanceAttributesToComponent() {
1059         final Component component = new Resource();
1060         component.setUniqueId(COMPONENT_ID);
1061         Map<String, List<ComponentInstanceAttribute>> map = new HashMap<>();
1062         List<ComponentInstanceAttribute> componentInstanceOutputList = new ArrayList<>();
1063         ComponentInstanceAttribute componentInstanceAttribute = new ComponentInstanceAttribute();
1064         componentInstanceAttribute.setComponentInstanceId(COMPONENT_ID);
1065         componentInstanceAttribute.setUniqueId(COMPONENT_ID);
1066         componentInstanceOutputList.add(componentInstanceAttribute);
1067         map.put("mock", componentInstanceOutputList);
1068         component.setComponentInstancesAttributes(map);
1069
1070         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock)
1071             .updateComponentInstanceAttribute(any(Component.class), anyString(), any(ComponentInstanceAttribute.class));
1072
1073         final Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> result
1074             = testInstance.addComponentInstanceAttributesToComponent(component, map);
1075
1076         assertNotNull(result);
1077         assertTrue(result.isLeft());
1078         assertFalse(result.left().value().isEmpty());
1079         assertSame(result.left().value(), map);
1080         verify(nodeTemplateOperationMock, times(1))
1081             .updateComponentInstanceAttribute(any(Component.class), anyString(), any(ComponentInstanceAttribute.class));
1082     }
1083
1084     @Test
1085     void test_updateAttributeOfComponent_success() {
1086         final GraphVertex graphVertex = getTopologyTemplateVertex();
1087         final String componentId = "componentId";
1088         final Component component = new Resource();
1089         component.setUniqueId(COMPONENT_ID);
1090         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock).updateToscaDataOfToscaElement(
1091             anyString(), eq(EdgeLabelEnum.ATTRIBUTES), eq(VertexTypeEnum.ATTRIBUTES), any(AttributeDefinition.class),
1092             eq(JsonPresentationFields.NAME));
1093         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(eq(componentId), any(JsonParseFlagEnum.class));
1094
1095         final ToscaElement toscaElement = getToscaElementForTest();
1096         final Map<String, AttributeDataDefinition> attributes = new HashMap<>();
1097         final AttributeDefinition attributeDefinition = new AttributeDefinition();
1098         attributeDefinition.setName("mock");
1099         attributes.put("mock", attributeDefinition);
1100         toscaElement.setAttributes(attributes);
1101         doReturn(Either.left(toscaElement)).when(topologyTemplateOperationMock)
1102             .getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class));
1103
1104         final Either<AttributeDefinition, StorageOperationStatus> result
1105             = testInstance.updateAttributeOfComponent(component, attributeDefinition);
1106         assertNotNull(result);
1107     }
1108
1109     @Test
1110     void test_updateAttributeOfComponent_isNotPresent() {
1111         final GraphVertex graphVertex = getTopologyTemplateVertex();
1112         final String componentId = "componentId";
1113         final Component component = new Resource();
1114         component.setUniqueId(COMPONENT_ID);
1115         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock).updateToscaDataOfToscaElement(
1116             anyString(), eq(EdgeLabelEnum.ATTRIBUTES), eq(VertexTypeEnum.ATTRIBUTES), any(AttributeDefinition.class),
1117             eq(JsonPresentationFields.NAME));
1118         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(eq(componentId), any(JsonParseFlagEnum.class));
1119
1120         final ToscaElement toscaElement = getToscaElementForTest();
1121         final Map<String, AttributeDataDefinition> attributes = new HashMap<>();
1122         final AttributeDefinition attributeDefinition = new AttributeDefinition();
1123         attributeDefinition.setName("mock");
1124         attributes.put("mock", attributeDefinition);
1125         toscaElement.setAttributes(attributes);
1126         doReturn(Either.left(toscaElement)).when(topologyTemplateOperationMock)
1127             .getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class));
1128
1129         final AttributeDefinition attributeDefinitionOneMore = new AttributeDefinition();
1130         attributeDefinitionOneMore.setName("Anothermock");
1131
1132         final Either<AttributeDefinition, StorageOperationStatus> result
1133             = testInstance.updateAttributeOfComponent(component, attributeDefinitionOneMore);
1134         assertNotNull(result);
1135     }
1136
1137     @Test
1138     void test_updateComponentInstanceAttributes() {
1139         final GraphVertex graphVertex = getTopologyTemplateVertex();
1140         final String componentId = "componentId";
1141         final Component component = new Resource();
1142         component.setUniqueId(COMPONENT_ID);
1143
1144         final List<ComponentInstanceAttribute> attributes = new ArrayList<>();
1145         final ComponentInstanceAttribute attributeDefinition = new ComponentInstanceAttribute();
1146         attributeDefinition.setName("mock");
1147         attributes.add(attributeDefinition);
1148
1149         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock).updateComponentInstanceAttributes(component, componentId, attributes);
1150
1151         final StorageOperationStatus result = testInstance.updateComponentInstanceAttributes(component, componentId, attributes);
1152         assertNotNull(result);
1153         assertEquals(StorageOperationStatus.OK, result);
1154         verify(nodeTemplateOperationMock, times(1)).updateComponentInstanceAttributes(component, componentId, attributes);
1155     }
1156
1157     @Test
1158     void test_updateComponentInstanceOutputs() {
1159         final GraphVertex graphVertex = getTopologyTemplateVertex();
1160         final String componentId = "componentId";
1161         final Component component = new Resource();
1162         component.setUniqueId(COMPONENT_ID);
1163
1164         final List<ComponentInstanceOutput> list = new ArrayList<>();
1165         final ComponentInstanceOutput output = new ComponentInstanceOutput();
1166         output.setName("mock");
1167         list.add(output);
1168
1169         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock).updateComponentInstanceOutputs(component, componentId, list);
1170
1171         final StorageOperationStatus result = testInstance.updateComponentInstanceOutputs(component, componentId, list);
1172         assertNotNull(result);
1173         assertEquals(StorageOperationStatus.OK, result);
1174         verify(nodeTemplateOperationMock, times(1)).updateComponentInstanceOutputs(component, componentId, list);
1175     }
1176
1177     @Test
1178     void test_deleteOutputOfResource() {
1179         final Component component = new Resource();
1180         component.setUniqueId(COMPONENT_ID);
1181
1182         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock)
1183             .deleteToscaDataElement(anyString(), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyString(), eq(JsonPresentationFields.NAME));
1184
1185         final StorageOperationStatus result = testInstance.deleteOutputOfResource(component, "mock");
1186         assertNotNull(result);
1187         assertEquals(StorageOperationStatus.OK, result);
1188         verify(nodeTypeOperationMock, times(1))
1189             .deleteToscaDataElement(anyString(), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyString(), eq(JsonPresentationFields.NAME));
1190     }
1191
1192     @Test
1193     void testDeleteResource_ResourceInUse() {
1194         GraphVertex graphVertex = getTopologyTemplateVertex();
1195         String invariantUuid = "1";
1196         graphVertex.setUniqueId(invariantUuid);
1197         GraphVertex usingComponent = getTopologyTemplateVertex();
1198         usingComponent.setUniqueId("2");
1199         Map<String, Object> metadataJson = new HashMap<>();
1200         metadataJson.put("COMPONENT_TYPE", "SERVICE");
1201         metadataJson.put("NAME", "serviceName");
1202         usingComponent.setMetadataJson(metadataJson);
1203         List<GraphVertex> inUseBy = new ArrayList<>();
1204         inUseBy.add(usingComponent);
1205         Map<String, Object> metadata = new HashMap<>();
1206         metadata.put("ex1", new Object());
1207         graphVertex.setMetadataJson(metadata);
1208         ToscaElement toscaElement = getToscaElementForTest();
1209         toscaElement.setUniqueId(invariantUuid);
1210         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1211         allResourcesToDelete.add(graphVertex);
1212
1213         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap())).
1214             thenReturn(allResourcesToDelete);
1215         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), eq(JsonParseFlagEnum.ParseAll))).thenReturn(Either.left(inUseBy));
1216
1217         final OperationException actualException = assertThrows(OperationException.class,
1218             () -> testInstance.deleteComponent(invariantUuid, NodeTypeEnum.Resource, true));
1219         assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualException.getActionStatus());
1220     }
1221
1222     @Test
1223     void testDeleteResource_WithTwoVersions() {
1224         GraphVertex graphVertex = getTopologyTemplateVertex();
1225         String invariantUuid = "1";
1226         graphVertex.setUniqueId(invariantUuid);
1227         Map<String, Object> metadata1 = new HashMap<>();
1228         metadata1.put("ex1", new Object());
1229         graphVertex.setMetadataJson(metadata1);
1230         ToscaElement toscaElement1 = getToscaElementForTest();
1231         toscaElement1.setUniqueId(invariantUuid);
1232         ToscaElement toscaElement2 = getToscaElementForTest();
1233         toscaElement2.setUniqueId("2");
1234         GraphVertex graphVertex2 = getTopologyTemplateVertex();
1235         graphVertex2.setUniqueId("2");
1236         Map<String, Object> metadata2 = new HashMap<>();
1237         metadata2.put("ex2", new Object());
1238         graphVertex.setMetadataJson(metadata2);
1239         List<GraphVertex> parentVertices = new ArrayList<>();
1240         parentVertices.add(graphVertex2);
1241         List<String> affectedComponentIds = new ArrayList<>();
1242         affectedComponentIds.add(graphVertex.getUniqueId());
1243         affectedComponentIds.add(graphVertex2.getUniqueId());
1244
1245         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1246             thenReturn(StorageOperationStatus.OK);
1247         when(graphLockOperationMock.lockComponent(graphVertex2.getUniqueId(), NodeTypeEnum.Resource)).
1248             thenReturn(StorageOperationStatus.OK);
1249         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement1));
1250         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex2)).thenReturn(Either.left(toscaElement2));
1251         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1252         allResourcesToDelete.add(graphVertex);
1253         allResourcesToDelete.add(graphVertex2);
1254         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap())).
1255             thenReturn(allResourcesToDelete);
1256         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1257         assertEquals(affectedComponentIds, testInstance.deleteComponent(invariantUuid, NodeTypeEnum.Resource, false));
1258     }
1259
1260     @Test
1261     void testDeleteResource_WithOneVersion() {
1262         GraphVertex graphVertex = getTopologyTemplateVertex();
1263         graphVertex.setUniqueId("1");
1264         Map<String, Object> metadata = new HashMap<>();
1265         metadata.put("ex1", new Object());
1266         graphVertex.setMetadataJson(metadata);
1267         ToscaElement toscaElement = getToscaElementForTest();
1268         List<String> affectedComponentIds = new ArrayList<>();
1269         affectedComponentIds.add(graphVertex.getUniqueId());
1270         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1271             thenReturn(StorageOperationStatus.OK);
1272         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
1273         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1274         allResourcesToDelete.add(graphVertex);
1275         when(janusGraphDaoMock.findAllVertexByInvariantUuid(graphVertex.getUniqueId(), Collections.emptyMap())).
1276             thenReturn(allResourcesToDelete);
1277         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1278         assertEquals(affectedComponentIds, testInstance.deleteComponent("1", NodeTypeEnum.Resource, true));
1279     }
1280
1281     @Test
1282     void testDeleteResource_FailDelete() {
1283         Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
1284         metadataProperties.put(GraphPropertyEnum.NAME, "graphVertex");
1285         GraphVertex graphVertex = getTopologyTemplateVertex();
1286         String invariantUUID = "1";
1287         graphVertex.setUniqueId(invariantUUID);
1288         graphVertex.setMetadataProperties(metadataProperties);
1289         ToscaElement toscaElement1 = getToscaElementForTest();
1290         toscaElement1.setUniqueId(invariantUUID);
1291         List<String> affectedComponentIds = new ArrayList<>();
1292         affectedComponentIds.add(graphVertex.getUniqueId());
1293         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1294         allResourcesToDelete.add(graphVertex);
1295
1296         when(janusGraphDaoMock.findAllVertexByInvariantUuid(graphVertex.getUniqueId(), Collections.emptyMap())).
1297             thenReturn(allResourcesToDelete);
1298         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1299             thenReturn(StorageOperationStatus.OK);
1300         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex))
1301             .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1302         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1303         StorageException actualException = assertThrows(StorageException.class,
1304             () -> testInstance.deleteComponent(invariantUUID, NodeTypeEnum.Resource, false));
1305         assertEquals(StorageOperationStatus.NOT_FOUND, actualException.getStorageOperationStatus());
1306         assertEquals(0, actualException.getParams().length);
1307     }
1308
1309     @Test
1310     void testDeleteResource_NotFound() {
1311         String invariantUUID = "12345";
1312         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).thenReturn(Collections.emptyList());
1313         assertEquals(0, testInstance.deleteComponent(invariantUUID, NodeTypeEnum.Resource, true).size());
1314     }
1315
1316     @Test
1317     void testCreateAndAssociateInputs_OK() {
1318         GraphVertex vertex = getTopologyTemplateVertex();
1319         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1320         when(topologyTemplateOperationMock.associateInputsToComponent(eq(vertex), anyMap(), anyString())).thenReturn(StorageOperationStatus.OK);
1321         Map<String, InputDefinition> inputs = new HashMap<>();
1322         inputs.put("1", new InputDefinition());
1323         inputs.put("2", new InputDefinition());
1324         final var result = testInstance.createAndAssociateInputs(inputs, COMPONENT_ID);
1325         assertTrue(result.isLeft());
1326         assertNotNull(result.left());
1327         assertEquals(2, result.left().value().size());
1328     }
1329
1330     @Test
1331     void testCreateAndAssociateInputs_NegativeAssociateInputsToComponentStatus() {
1332         GraphVertex vertex = getTopologyTemplateVertex();
1333         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1334         when(topologyTemplateOperationMock.associateInputsToComponent(eq(vertex), anyMap(), anyString()))
1335             .thenReturn(StorageOperationStatus.NOT_FOUND);
1336         final var result = testInstance.createAndAssociateInputs(new HashMap<>(), COMPONENT_ID);
1337         assertTrue(result.isRight());
1338         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1339     }
1340
1341     @Test
1342     void testCreateAndAssociateInputs_componentNotFound() {
1343         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
1344         final var result = testInstance.createAndAssociateInputs(new HashMap<>(), COMPONENT_ID);
1345         assertTrue(result.isRight());
1346         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1347     }
1348
1349     @Test
1350     void testCreateAndAssociateOutputs_OK() {
1351         GraphVertex vertex = getTopologyTemplateVertex();
1352         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1353         when(topologyTemplateOperationMock.associateOutputsToComponent(eq(vertex), anyMap(), anyString())).thenReturn(StorageOperationStatus.OK);
1354         Map<String, OutputDefinition> outputs = new HashMap<>();
1355         outputs.put("1", new OutputDefinition());
1356         outputs.put("2", new OutputDefinition());
1357         final var result = testInstance.createAndAssociateOutputs(outputs, COMPONENT_ID);
1358         assertTrue(result.isLeft());
1359         assertNotNull(result.left());
1360         assertEquals(2, result.left().value().size());
1361     }
1362
1363     @Test
1364     void testCreateAndAssociateOutputs_NegativeAssociateOutputsToComponentStatus() {
1365         GraphVertex vertex = getTopologyTemplateVertex();
1366         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1367         when(topologyTemplateOperationMock.associateOutputsToComponent(eq(vertex), anyMap(), anyString()))
1368             .thenReturn(StorageOperationStatus.NOT_FOUND);
1369         final var result = testInstance.createAndAssociateOutputs(new HashMap<>(), COMPONENT_ID);
1370         assertTrue(result.isRight());
1371         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1372     }
1373
1374     @Test
1375     void testCreateAndAssociateOutputs_componentNotFound() {
1376         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
1377         final var result = testInstance.createAndAssociateOutputs(new HashMap<>(), COMPONENT_ID);
1378         assertTrue(result.isRight());
1379         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1380     }
1381
1382     private StorageOperationStatus associateRequirementsToServiceWithStatus(StorageOperationStatus status) {
1383         Map<String, ListRequirementDataDefinition> requirementsMap = new HashedMap();
1384         String componentId = "componentid";
1385
1386         ListRequirementDataDefinition listRequirementDataDefinition1 = new ListRequirementDataDefinition();
1387         requirementsMap.put("requirements1", listRequirementDataDefinition1);
1388
1389         GraphVertex vertex;
1390         if (status == StorageOperationStatus.OK) {
1391             vertex = getTopologyTemplateVertex();
1392         } else {
1393             vertex = getNodeTypeVertex();
1394         }
1395
1396         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1397         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
1398         when(topologyTemplateOperationMock.associateElementToData(eq(vertex),
1399             eq(VertexTypeEnum.REQUIREMENTS), eq(EdgeLabelEnum.REQUIREMENTS), anyMap())).thenReturn(Either.right(status));
1400         return testInstance.associateRequirementsToService(requirementsMap, componentId);
1401     }
1402
1403     private Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponentWithStatus(StorageOperationStatus status) {
1404         PolicyDefinition policy = new PolicyDefinition();
1405         String componentId = "componentId";
1406         int counter = 0;
1407         GraphVertex vertex;
1408         if (status == StorageOperationStatus.OK) {
1409             vertex = getTopologyTemplateVertex();
1410         } else {
1411             vertex = getNodeTypeVertex();
1412         }
1413         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1414         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)).thenReturn(getVertexEither);
1415         if (status == StorageOperationStatus.OK) {
1416             when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status);
1417         }
1418         return testInstance.associatePolicyToComponent(componentId, policy, counter);
1419     }
1420
1421     private Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponentWithStatus(StorageOperationStatus status) {
1422         PolicyDefinition policy = new PolicyDefinition();
1423         String componentId = "componentId";
1424         GraphVertex vertex = getTopologyTemplateVertex();
1425         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1426         when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status);
1427         return testInstance.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.NONE);
1428     }
1429
1430     private void removePolicyFromComponentWithStatus(StorageOperationStatus status) {
1431         String componentId = "componentId";
1432         String policyId = "policyId";
1433         GraphVertex vertex = getTopologyTemplateVertex();
1434         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1435         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
1436         when(topologyTemplateOperationMock.removePolicyFromToscaElement(vertex, policyId)).thenReturn(status);
1437         StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId);
1438         assertSame(result, status);
1439     }
1440
1441     private List<GraphVertex> getMockVertices(int numOfVertices) {
1442         return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList());
1443     }
1444
1445     private ToscaElement getResourceToscaElement(String id) {
1446         ToscaElement toscaElement = new TopologyTemplate();
1447         toscaElement.setMetadata(new HashMap<>());
1448         toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE");
1449         toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id);
1450         return toscaElement;
1451     }
1452
1453     private GraphVertex getTopologyTemplateVertex() {
1454         GraphVertex graphVertex = new GraphVertex();
1455         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1456         return graphVertex;
1457     }
1458
1459     private GraphVertex getNodeTypeVertex() {
1460         GraphVertex graphVertex = new GraphVertex();
1461         graphVertex.setLabel(VertexTypeEnum.NODE_TYPE);
1462         return graphVertex;
1463     }
1464
1465 }