f32c5e2842dee6a66f70c690da5eff5f780e0323
[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 testGetBySystemNameAndVersion() {
653         Either<Component, StorageOperationStatus> result;
654         String sysName = "sysName";
655         String version = "version";
656         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
657         ToscaElement toscaElement = getToscaElementForTest();
658         List<GraphVertex> componentVertices = new ArrayList<>();
659         GraphVertex graphVertex = getTopologyTemplateVertex();
660         componentVertices.add(graphVertex);
661         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
662         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
663
664         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName);
665         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name());
666         propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
667
668         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
669
670         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll))
671             .thenReturn(Either.left(componentVertices));
672         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
673             .thenReturn(Either.left(toscaElement));
674         result = testInstance.getBySystemNameAndVersion(componentTypeEnum, sysName, version);
675         assertTrue(result.isLeft());
676         assertNotNull(result.left().value());
677     }
678
679     @Test
680     void testGetCompByNameAndVersion() {
681         Either<Component, StorageOperationStatus> result;
682         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
683         String name = "name";
684         String version = "1.0";
685         JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll;
686         List<GraphVertex> graphVertexList = new ArrayList<>();
687         GraphVertex graphVertex = getTopologyTemplateVertex();
688         graphVertexList.add(graphVertex);
689         ToscaElement toscaElement = getToscaElementForTest();
690         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
691         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
692
693         hasProperties.put(GraphPropertyEnum.NAME, name);
694         hasProperties.put(GraphPropertyEnum.VERSION, version);
695         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
696         hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
697         when(janusGraphDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList));
698         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class)))
699             .thenReturn(Either.left(toscaElement));
700         result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag);
701         assertTrue(result.isLeft());
702     }
703
704     private ToscaElement getToscaElementForTest() {
705         ToscaElement toscaElement = new TopologyTemplate();
706         toscaElement.setComponentType(ComponentTypeEnum.RESOURCE);
707         return toscaElement;
708     }
709
710     @Test
711     void addDataTypesToComponentSuccessTest() {
712         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK);
713         assertTrue(result.isLeft());
714     }
715
716     @Test
717     void addDataTypesToComponentFailureTest_BadRequest() {
718         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
719         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
720     }
721
722     private Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) {
723         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
724         String componentId = "componentid";
725         String Id = "id";
726
727         PropertyDefinition noDefaultProp = new PropertyDefinition();
728         noDefaultProp.setName("noDefaultProp");
729         PropertyDefinition prop1 = new PropertyDefinition();
730         prop1.setDefaultValue("def1");
731         prop1.setName("prop1");
732         PropertyDefinition prop2 = new PropertyDefinition();
733         prop2.setType("dataType1");
734         prop2.setName("prop2");
735         PropertyDefinition prop3 = new PropertyDefinition();
736         prop3.setDefaultValue("def3");
737         prop3.setName("prop3");
738
739         DataTypeDefinition noDefaultValue = new DataTypeDefinition();
740         noDefaultValue.setProperties(Collections.singletonList(noDefaultProp));
741         noDefaultValue.setDerivedFromName("name0");
742
743         DataTypeDefinition dataType1 = new DataTypeDefinition();
744         dataType1.setProperties(Arrays.asList(prop1, prop3));
745         dataType1.setName("name1");
746         dataType1.setDerivedFromName("derivedfromname1");
747
748         DataTypeDefinition dataType2 = new DataTypeDefinition();
749         dataType2.setDerivedFrom(dataType1);
750         dataType2.setName("name2");
751         dataType2.setDerivedFromName("derivedfromname2");
752
753         DataTypeDefinition dataType3 = new DataTypeDefinition();
754         dataType3.setProperties(Collections.singletonList(prop2));
755         dataType3.setDerivedFrom(noDefaultValue);
756         dataType3.setName("name3");
757         dataType3.setDerivedFromName("derivedfromname3");
758
759         dataTypes.put("noDefault", noDefaultValue);
760         dataTypes.put("dataType1", dataType1);
761         dataTypes.put("dataType2", dataType2);
762         dataTypes.put("dataType3", dataType3);
763
764         GraphVertex vertex;
765         if (status == StorageOperationStatus.OK) {
766             vertex = getTopologyTemplateVertex();
767         } else {
768             vertex = getNodeTypeVertex();
769         }
770         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
771         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
772         when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex),
773             eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status);
774         return testInstance.addDataTypesToComponent(dataTypes, componentId);
775     }
776
777     @Test
778     void testDataTypesToComponentFailureTest_NotFound() {
779         Either<List<DataTypeDefinition>, StorageOperationStatus> result;
780         String componentId = "componentId";
781         GraphVertex vertex = getNodeTypeVertex();
782         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
783         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
784             JanusGraphOperationStatus.NOT_FOUND));
785         result = testInstance.addDataTypesToComponent(dataTypes, componentId);
786         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
787     }
788
789     @Test
790     void testDeleteDataTypeOfComponent() {
791         Component component = new Resource();
792         String id = "id";
793         component.setUniqueId(id);
794
795         DataTypeDefinition dataType1 = new DataTypeDefinition();
796         dataType1.setName("name1");
797         Map<String, DataTypeDataDefinition> dataTypeDataMap = new HashMap<>();
798         dataTypeDataMap.put("datatype1", dataType1);
799         List<DataTypeDefinition> dataTypeMap = dataTypeDataMap.values().stream().map(e -> {
800             return new DataTypeDefinition(e);
801         }).collect(Collectors.toList());
802         component.setDataTypes(dataTypeMap);
803         GraphVertex graphVertex = getTopologyTemplateVertex();
804         assertNull(testInstance.deleteDataTypeOfComponent(component, "datatype1"));
805     }
806
807     @Test
808     void testAddComponentInstancePropertiesToComponent() {
809         // set up component object
810         Component component = new Resource();
811         component.setUniqueId(COMPONENT_ID);
812         List<ComponentInstanceProperty> instanceProps = new ArrayList<>();
813         ComponentInstanceProperty instanceProp = new ComponentInstanceProperty();
814         instanceProp.setName(PROPERTY1_NAME);
815         instanceProp.setType(PROPERTY1_TYPE);
816         instanceProps.add(instanceProp);
817         instanceProp = new ComponentInstanceProperty();
818         instanceProp.setName(PROPERTY2_NAME);
819         instanceProp.setType(PROPERTY2_TYPE);
820         instanceProps.add(instanceProp);
821         Map<String, List<ComponentInstanceProperty>> instancePropsMap =
822             Collections.singletonMap(COMPONENT_ID, instanceProps);
823         component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>()));
824
825         when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any()))
826             .thenReturn(StorageOperationStatus.OK);
827
828         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> result =
829             testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap);
830         assertTrue(result.isLeft());
831         verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any());
832         List<ComponentInstanceProperty> resultProps = result.left().value().get(COMPONENT_ID);
833         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME)));
834         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME)));
835     }
836
837     @Test
838     void testAddComponentInstanceToTopologyTemplate_ServiceProxy() {
839         Component containerComponent = new Service();
840         Component originalComponent = new Service();
841         ComponentInstance componentInstance = new ComponentInstance();
842         ComponentInstance existingComponentInstance = new ComponentInstance();
843         User user = new User();
844
845         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
846
847         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
848         originalComponent.setIcon(ICON_NAME);
849
850         componentInstance.setOriginType(OriginTypeEnum.ServiceProxy);
851         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
852
853         List<ComponentInstance> existingInstances = new ArrayList<>();
854         existingComponentInstance.setNormalizedName(SERVICE_PROXY_INSTANCE0_NAME);
855         existingInstances.add(existingComponentInstance);
856         containerComponent.setComponentInstances(existingInstances);
857
858         when(nodeTemplateOperationMock
859             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
860             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
861         TopologyTemplate topologyTemplate = new TopologyTemplate();
862         // preset COMPONENT_TYPE field for internal ModelConverter call
863         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
864         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
865             .thenReturn(Either.left(topologyTemplate));
866
867         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
868             testInstance.addComponentInstanceToTopologyTemplate(
869                 containerComponent, originalComponent, componentInstance, false, user);
870
871         assertTrue(result.isLeft());
872         assertEquals(ICON_NAME, componentInstance.getIcon());
873         assertEquals(COMPONENT_ID, result.left().value().getRight());
874         // the instance counter must be 1 because the service proxy instance with suffix 0 already exists.
875         verify(nodeTemplateOperationMock, times(1))
876             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
877     }
878
879     @Test
880     void testAddComponentInstanceToTopologyTemplate_ServiceSubstitution() {
881         Component containerComponent = new Service();
882         Component originalComponent = new Service();
883         ComponentInstance componentInstance = new ComponentInstance();
884         ComponentInstance existingComponentInstance = new ComponentInstance();
885         User user = new User();
886
887         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
888
889         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
890         originalComponent.setIcon(ICON_NAME);
891
892         componentInstance.setOriginType(OriginTypeEnum.ServiceSubstitution);
893         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
894
895         List<ComponentInstance> existingInstances = new ArrayList<>();
896         existingComponentInstance.setNormalizedName(SERVICE_SUBSTITUTION_INSTANCE0_NAME);
897         existingInstances.add(existingComponentInstance);
898         containerComponent.setComponentInstances(existingInstances);
899
900         when(nodeTemplateOperationMock
901             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
902             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
903         TopologyTemplate topologyTemplate = new TopologyTemplate();
904         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
905         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
906             .thenReturn(Either.left(topologyTemplate));
907
908         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
909             testInstance.addComponentInstanceToTopologyTemplate(
910                 containerComponent, originalComponent, componentInstance, false, user);
911
912         assertTrue(result.isLeft());
913         assertEquals(ICON_NAME, componentInstance.getIcon());
914         assertEquals(COMPONENT_ID, result.left().value().getRight());
915         verify(nodeTemplateOperationMock, times(1))
916             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
917     }
918
919     @Test
920     void testUpdateComponentInstanceRequirement() {
921         String containerComponentId = "containerComponentId";
922         String componentInstanceUniqueId = "componentInstanceUniqueId";
923         RequirementDataDefinition requirementDataDefinition = Mockito.mock(RequirementDataDefinition.class);
924
925         when(nodeTemplateOperationMock.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition))
926             .thenReturn(StorageOperationStatus.OK);
927         StorageOperationStatus result = testInstance
928             .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
929         assertEquals(StorageOperationStatus.OK, result);
930         verify(nodeTemplateOperationMock, times(1))
931             .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
932
933     }
934
935     @Test
936     void associateCapabilitiesToServiceFailureTest() {
937         StorageOperationStatus result = associateCapabilitiesToServiceWithStatus(StorageOperationStatus.BAD_REQUEST);
938         assertSame(StorageOperationStatus.BAD_REQUEST, result);
939     }
940
941     @Test
942     void associateCapabilitiesToServiceSuccessTest() {
943         StorageOperationStatus result = associateCapabilitiesToServiceWithStatus(StorageOperationStatus.OK);
944         assertSame(StorageOperationStatus.OK, result);
945     }
946
947     private StorageOperationStatus associateCapabilitiesToServiceWithStatus(StorageOperationStatus status) {
948         Map<String, ListCapabilityDataDefinition> capabilitiesMap = new HashedMap();
949         String componentId = "componentid";
950
951         ListCapabilityDataDefinition listCapabilityDataDefinition1 = new ListCapabilityDataDefinition();
952         capabilitiesMap.put("capabilities1", listCapabilityDataDefinition1);
953
954         GraphVertex vertex;
955         if (status == StorageOperationStatus.OK) {
956             vertex = getTopologyTemplateVertex();
957         } else {
958             vertex = getNodeTypeVertex();
959         }
960
961         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
962         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
963         when(topologyTemplateOperationMock.associateElementToData(eq(vertex),
964             eq(VertexTypeEnum.CAPABILITIES), eq(EdgeLabelEnum.CAPABILITIES), anyMap())).thenReturn(Either.right(status));
965         return testInstance.associateCapabilitiesToService(capabilitiesMap, componentId);
966     }
967
968     @Test
969     void associateRequirementsToServiceFailureTest() {
970         StorageOperationStatus result = associateRequirementsToServiceWithStatus(StorageOperationStatus.BAD_REQUEST);
971         assertSame(StorageOperationStatus.BAD_REQUEST, result);
972     }
973
974     @Test
975     void associateRequirementsToServiceSuccessTest() {
976         StorageOperationStatus result = associateRequirementsToServiceWithStatus(StorageOperationStatus.OK);
977         assertSame(StorageOperationStatus.OK, result);
978     }
979
980     @Test
981     void test_addOutputsToComponent() {
982         final GraphVertex graphVertex = getTopologyTemplateVertex();
983
984         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse);
985         doReturn(StorageOperationStatus.OK).when(topologyTemplateOperationMock)
986             .addToscaDataToToscaElement(
987                 any(GraphVertex.class), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyMap(), eq(JsonPresentationFields.NAME));
988
989         final Map<String, OutputDefinition> outputs = new HashMap<>();
990         final OutputDefinition outputDefinition = new OutputDefinition();
991         outputs.put("mock", outputDefinition);
992         final Either<List<OutputDefinition>, StorageOperationStatus> result = testInstance.addOutputsToComponent(outputs, COMPONENT_ID);
993         assertNotNull(result);
994         assertTrue(result.isLeft());
995         assertFalse(result.left().value().isEmpty());
996         assertThat(result.left().value().get(0)).isInstanceOf(OutputDefinition.class);
997         verify(janusGraphDaoMock, times(1)).getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse);
998         verify(topologyTemplateOperationMock, times(1)).addToscaDataToToscaElement(
999             any(GraphVertex.class), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyMap(), eq(JsonPresentationFields.NAME));
1000     }
1001
1002     @Test
1003     void test_addComponentInstanceOutputsToComponent_updateComponentInstanceOutput() {
1004         final Component component = new Resource();
1005         component.setUniqueId(COMPONENT_ID);
1006         final Map<String, List<ComponentInstanceOutput>> map = new HashMap<>();
1007         final List<ComponentInstanceOutput> componentInstanceOutputList = new ArrayList<>();
1008         final ComponentInstanceOutput componentInstanceOutput = new ComponentInstanceOutput();
1009         componentInstanceOutput.setComponentInstanceId(COMPONENT_ID);
1010         componentInstanceOutput.setComponentInstanceName(COMPONENT_ID);
1011         componentInstanceOutput.setName(COMPONENT_ID);
1012         componentInstanceOutputList.add(componentInstanceOutput);
1013         map.put("mock", componentInstanceOutputList);
1014         component.setComponentInstancesOutputs(map);
1015
1016         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock)
1017             .updateComponentInstanceOutput(any(Component.class), anyString(), any(ComponentInstanceOutput.class));
1018
1019         final Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> result
1020             = testInstance.addComponentInstanceOutputsToComponent(component, map);
1021         assertNotNull(result);
1022         assertTrue(result.isLeft());
1023         assertFalse(result.left().value().isEmpty());
1024         assertSame(result.left().value(), map);
1025         verify(nodeTemplateOperationMock, times(1))
1026             .updateComponentInstanceOutput(any(Component.class), anyString(), any(ComponentInstanceOutput.class));
1027
1028     }
1029
1030     @Test
1031     void test_addComponentInstanceOutputsToComponent_addComponentInstanceOutput() {
1032         final Component component = new Resource();
1033         component.setUniqueId(COMPONENT_ID);
1034         Map<String, List<ComponentInstanceOutput>> map = new HashMap<>();
1035         List<ComponentInstanceOutput> componentInstanceOutputList = new ArrayList<>();
1036         ComponentInstanceOutput componentInstanceOutput = new ComponentInstanceOutput();
1037         componentInstanceOutput.setComponentInstanceId(COMPONENT_ID);
1038         componentInstanceOutput.setComponentInstanceName(COMPONENT_ID);
1039         componentInstanceOutput.setName(COMPONENT_ID);
1040         componentInstanceOutputList.add(componentInstanceOutput);
1041         map.put("mock", componentInstanceOutputList);
1042         component.setComponentInstancesOutputs(map);
1043
1044         map = new HashMap<>();
1045         componentInstanceOutputList = new ArrayList<>();
1046         componentInstanceOutput = new ComponentInstanceOutput();
1047         componentInstanceOutput.setComponentInstanceId("mock");
1048         componentInstanceOutput.setComponentInstanceName("mock");
1049         componentInstanceOutput.setName("mock");
1050         componentInstanceOutputList.add(componentInstanceOutput);
1051         map.put("mock", componentInstanceOutputList);
1052
1053         final Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> result = testInstance
1054             .addComponentInstanceOutputsToComponent(component, map);
1055         assertNotNull(result);
1056         assertTrue(result.isRight());
1057     }
1058
1059     @Test
1060     void test_addComponentInstanceAttributesToComponent() {
1061         final Component component = new Resource();
1062         component.setUniqueId(COMPONENT_ID);
1063         Map<String, List<ComponentInstanceAttribute>> map = new HashMap<>();
1064         List<ComponentInstanceAttribute> componentInstanceOutputList = new ArrayList<>();
1065         ComponentInstanceAttribute componentInstanceAttribute = new ComponentInstanceAttribute();
1066         componentInstanceAttribute.setComponentInstanceId(COMPONENT_ID);
1067         componentInstanceAttribute.setUniqueId(COMPONENT_ID);
1068         componentInstanceOutputList.add(componentInstanceAttribute);
1069         map.put("mock", componentInstanceOutputList);
1070         component.setComponentInstancesAttributes(map);
1071
1072         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock)
1073             .updateComponentInstanceAttribute(any(Component.class), anyString(), any(ComponentInstanceAttribute.class));
1074
1075         final Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> result
1076             = testInstance.addComponentInstanceAttributesToComponent(component, map);
1077
1078         assertNotNull(result);
1079         assertTrue(result.isLeft());
1080         assertFalse(result.left().value().isEmpty());
1081         assertSame(result.left().value(), map);
1082         verify(nodeTemplateOperationMock, times(1))
1083             .updateComponentInstanceAttribute(any(Component.class), anyString(), any(ComponentInstanceAttribute.class));
1084     }
1085
1086     @Test
1087     void test_updateAttributeOfComponent_success() {
1088         final GraphVertex graphVertex = getTopologyTemplateVertex();
1089         final String componentId = "componentId";
1090         final Component component = new Resource();
1091         component.setUniqueId(COMPONENT_ID);
1092         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock).updateToscaDataOfToscaElement(
1093             anyString(), eq(EdgeLabelEnum.ATTRIBUTES), eq(VertexTypeEnum.ATTRIBUTES), any(AttributeDefinition.class),
1094             eq(JsonPresentationFields.NAME));
1095         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(eq(componentId), any(JsonParseFlagEnum.class));
1096
1097         final ToscaElement toscaElement = getToscaElementForTest();
1098         final Map<String, AttributeDataDefinition> attributes = new HashMap<>();
1099         final AttributeDefinition attributeDefinition = new AttributeDefinition();
1100         attributeDefinition.setName("mock");
1101         attributes.put("mock", attributeDefinition);
1102         toscaElement.setAttributes(attributes);
1103         doReturn(Either.left(toscaElement)).when(topologyTemplateOperationMock)
1104             .getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class));
1105
1106         final Either<AttributeDefinition, StorageOperationStatus> result
1107             = testInstance.updateAttributeOfComponent(component, attributeDefinition);
1108         assertNotNull(result);
1109     }
1110
1111     @Test
1112     void test_updateAttributeOfComponent_isNotPresent() {
1113         final GraphVertex graphVertex = getTopologyTemplateVertex();
1114         final String componentId = "componentId";
1115         final Component component = new Resource();
1116         component.setUniqueId(COMPONENT_ID);
1117         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock).updateToscaDataOfToscaElement(
1118             anyString(), eq(EdgeLabelEnum.ATTRIBUTES), eq(VertexTypeEnum.ATTRIBUTES), any(AttributeDefinition.class),
1119             eq(JsonPresentationFields.NAME));
1120         doReturn(Either.left(graphVertex)).when(janusGraphDaoMock).getVertexById(eq(componentId), any(JsonParseFlagEnum.class));
1121
1122         final ToscaElement toscaElement = getToscaElementForTest();
1123         final Map<String, AttributeDataDefinition> attributes = new HashMap<>();
1124         final AttributeDefinition attributeDefinition = new AttributeDefinition();
1125         attributeDefinition.setName("mock");
1126         attributes.put("mock", attributeDefinition);
1127         toscaElement.setAttributes(attributes);
1128         doReturn(Either.left(toscaElement)).when(topologyTemplateOperationMock)
1129             .getToscaElement(ArgumentMatchers.eq(graphVertex), any(ComponentParametersView.class));
1130
1131         final AttributeDefinition attributeDefinitionOneMore = new AttributeDefinition();
1132         attributeDefinitionOneMore.setName("Anothermock");
1133
1134         final Either<AttributeDefinition, StorageOperationStatus> result
1135             = testInstance.updateAttributeOfComponent(component, attributeDefinitionOneMore);
1136         assertNotNull(result);
1137     }
1138
1139     @Test
1140     void test_updateComponentInstanceAttributes() {
1141         final GraphVertex graphVertex = getTopologyTemplateVertex();
1142         final String componentId = "componentId";
1143         final Component component = new Resource();
1144         component.setUniqueId(COMPONENT_ID);
1145
1146         final List<ComponentInstanceAttribute> attributes = new ArrayList<>();
1147         final ComponentInstanceAttribute attributeDefinition = new ComponentInstanceAttribute();
1148         attributeDefinition.setName("mock");
1149         attributes.add(attributeDefinition);
1150
1151         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock).updateComponentInstanceAttributes(component, componentId, attributes);
1152
1153         final StorageOperationStatus result = testInstance.updateComponentInstanceAttributes(component, componentId, attributes);
1154         assertNotNull(result);
1155         assertEquals(StorageOperationStatus.OK, result);
1156         verify(nodeTemplateOperationMock, times(1)).updateComponentInstanceAttributes(component, componentId, attributes);
1157     }
1158
1159     @Test
1160     void test_updateComponentInstanceOutputs() {
1161         final GraphVertex graphVertex = getTopologyTemplateVertex();
1162         final String componentId = "componentId";
1163         final Component component = new Resource();
1164         component.setUniqueId(COMPONENT_ID);
1165
1166         final List<ComponentInstanceOutput> list = new ArrayList<>();
1167         final ComponentInstanceOutput output = new ComponentInstanceOutput();
1168         output.setName("mock");
1169         list.add(output);
1170
1171         doReturn(StorageOperationStatus.OK).when(nodeTemplateOperationMock).updateComponentInstanceOutputs(component, componentId, list);
1172
1173         final StorageOperationStatus result = testInstance.updateComponentInstanceOutputs(component, componentId, list);
1174         assertNotNull(result);
1175         assertEquals(StorageOperationStatus.OK, result);
1176         verify(nodeTemplateOperationMock, times(1)).updateComponentInstanceOutputs(component, componentId, list);
1177     }
1178
1179     @Test
1180     void test_deleteOutputOfResource() {
1181         final Component component = new Resource();
1182         component.setUniqueId(COMPONENT_ID);
1183
1184         doReturn(StorageOperationStatus.OK).when(nodeTypeOperationMock)
1185             .deleteToscaDataElement(anyString(), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyString(), eq(JsonPresentationFields.NAME));
1186
1187         final StorageOperationStatus result = testInstance.deleteOutputOfResource(component, "mock");
1188         assertNotNull(result);
1189         assertEquals(StorageOperationStatus.OK, result);
1190         verify(nodeTypeOperationMock, times(1))
1191             .deleteToscaDataElement(anyString(), eq(EdgeLabelEnum.OUTPUTS), eq(VertexTypeEnum.OUTPUTS), anyString(), eq(JsonPresentationFields.NAME));
1192     }
1193
1194     @Test
1195     void testDeleteResource_ResourceInUse() {
1196         GraphVertex graphVertex = getTopologyTemplateVertex();
1197         String invariantUuid = "1";
1198         graphVertex.setUniqueId(invariantUuid);
1199         GraphVertex usingComponent = getTopologyTemplateVertex();
1200         usingComponent.setUniqueId("2");
1201         Map<String, Object> metadataJson = new HashMap<>();
1202         metadataJson.put("COMPONENT_TYPE", "SERVICE");
1203         metadataJson.put("NAME", "serviceName");
1204         usingComponent.setMetadataJson(metadataJson);
1205         List<GraphVertex> inUseBy = new ArrayList<>();
1206         inUseBy.add(usingComponent);
1207         Map<String, Object> metadata = new HashMap<>();
1208         metadata.put("ex1", new Object());
1209         graphVertex.setMetadataJson(metadata);
1210         ToscaElement toscaElement = getToscaElementForTest();
1211         toscaElement.setUniqueId(invariantUuid);
1212         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1213         allResourcesToDelete.add(graphVertex);
1214
1215         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap())).
1216             thenReturn(allResourcesToDelete);
1217         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), eq(JsonParseFlagEnum.ParseAll))).thenReturn(Either.left(inUseBy));
1218
1219         final OperationException actualException = assertThrows(OperationException.class,
1220             () -> testInstance.deleteComponent(invariantUuid, NodeTypeEnum.Resource, true));
1221         assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualException.getActionStatus());
1222     }
1223
1224     @Test
1225     void testDeleteResource_WithTwoVersions() {
1226         GraphVertex graphVertex = getTopologyTemplateVertex();
1227         String invariantUuid = "1";
1228         graphVertex.setUniqueId(invariantUuid);
1229         Map<String, Object> metadata1 = new HashMap<>();
1230         metadata1.put("ex1", new Object());
1231         graphVertex.setMetadataJson(metadata1);
1232         ToscaElement toscaElement1 = getToscaElementForTest();
1233         toscaElement1.setUniqueId(invariantUuid);
1234         ToscaElement toscaElement2 = getToscaElementForTest();
1235         toscaElement2.setUniqueId("2");
1236         GraphVertex graphVertex2 = getTopologyTemplateVertex();
1237         graphVertex2.setUniqueId("2");
1238         Map<String, Object> metadata2 = new HashMap<>();
1239         metadata2.put("ex2", new Object());
1240         graphVertex.setMetadataJson(metadata2);
1241         List<GraphVertex> parentVertices = new ArrayList<>();
1242         parentVertices.add(graphVertex2);
1243         List<String> affectedComponentIds = new ArrayList<>();
1244         affectedComponentIds.add(graphVertex.getUniqueId());
1245         affectedComponentIds.add(graphVertex2.getUniqueId());
1246
1247         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1248             thenReturn(StorageOperationStatus.OK);
1249         when(graphLockOperationMock.lockComponent(graphVertex2.getUniqueId(), NodeTypeEnum.Resource)).
1250             thenReturn(StorageOperationStatus.OK);
1251         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement1));
1252         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex2)).thenReturn(Either.left(toscaElement2));
1253         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1254         allResourcesToDelete.add(graphVertex);
1255         allResourcesToDelete.add(graphVertex2);
1256         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUuid, Collections.emptyMap())).
1257             thenReturn(allResourcesToDelete);
1258         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1259         assertEquals(affectedComponentIds, testInstance.deleteComponent(invariantUuid, NodeTypeEnum.Resource, false));
1260     }
1261
1262     @Test
1263     void testDeleteResource_WithOneVersion() {
1264         GraphVertex graphVertex = getTopologyTemplateVertex();
1265         graphVertex.setUniqueId("1");
1266         Map<String, Object> metadata = new HashMap<>();
1267         metadata.put("ex1", new Object());
1268         graphVertex.setMetadataJson(metadata);
1269         ToscaElement toscaElement = getToscaElementForTest();
1270         List<String> affectedComponentIds = new ArrayList<>();
1271         affectedComponentIds.add(graphVertex.getUniqueId());
1272         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1273             thenReturn(StorageOperationStatus.OK);
1274         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
1275         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1276         allResourcesToDelete.add(graphVertex);
1277         when(janusGraphDaoMock.findAllVertexByInvariantUuid(graphVertex.getUniqueId(), Collections.emptyMap())).
1278             thenReturn(allResourcesToDelete);
1279         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1280         assertEquals(affectedComponentIds, testInstance.deleteComponent("1", NodeTypeEnum.Resource, true));
1281     }
1282
1283     @Test
1284     void testDeleteResource_FailDelete() {
1285         Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
1286         metadataProperties.put(GraphPropertyEnum.NAME, "graphVertex");
1287         GraphVertex graphVertex = getTopologyTemplateVertex();
1288         String invariantUUID = "1";
1289         graphVertex.setUniqueId(invariantUUID);
1290         graphVertex.setMetadataProperties(metadataProperties);
1291         ToscaElement toscaElement1 = getToscaElementForTest();
1292         toscaElement1.setUniqueId(invariantUUID);
1293         List<String> affectedComponentIds = new ArrayList<>();
1294         affectedComponentIds.add(graphVertex.getUniqueId());
1295         List<GraphVertex> allResourcesToDelete = new ArrayList<>();
1296         allResourcesToDelete.add(graphVertex);
1297
1298         when(janusGraphDaoMock.findAllVertexByInvariantUuid(graphVertex.getUniqueId(), Collections.emptyMap())).
1299             thenReturn(allResourcesToDelete);
1300         when(graphLockOperationMock.lockComponent(graphVertex.getUniqueId(), NodeTypeEnum.Resource)).
1301             thenReturn(StorageOperationStatus.OK);
1302         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex))
1303             .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1304         when(janusGraphDaoMock.getParentVertices(any(GraphVertex.class), any(), any())).thenReturn(Either.right(JanusGraphOperationStatus.OK));
1305         StorageException actualException = assertThrows(StorageException.class,
1306             () -> testInstance.deleteComponent(invariantUUID, NodeTypeEnum.Resource, false));
1307         assertEquals(StorageOperationStatus.NOT_FOUND, actualException.getStorageOperationStatus());
1308         assertEquals(0, actualException.getParams().length);
1309     }
1310
1311     @Test
1312     void testDeleteResource_NotFound() {
1313         String invariantUUID = "12345";
1314         when(janusGraphDaoMock.findAllVertexByInvariantUuid(invariantUUID, Collections.emptyMap())).thenReturn(Collections.emptyList());
1315         assertEquals(0, testInstance.deleteComponent(invariantUUID, NodeTypeEnum.Resource, true).size());
1316     }
1317
1318     @Test
1319     void testCreateAndAssociateInputs_OK() {
1320         GraphVertex vertex = getTopologyTemplateVertex();
1321         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1322         when(topologyTemplateOperationMock.associateInputsToComponent(eq(vertex), anyMap(), anyString())).thenReturn(StorageOperationStatus.OK);
1323         Map<String, InputDefinition> inputs = new HashMap<>();
1324         inputs.put("1", new InputDefinition());
1325         inputs.put("2", new InputDefinition());
1326         final var result = testInstance.createAndAssociateInputs(inputs, COMPONENT_ID);
1327         assertTrue(result.isLeft());
1328         assertNotNull(result.left());
1329         assertEquals(2, result.left().value().size());
1330     }
1331
1332     @Test
1333     void testCreateAndAssociateInputs_NegativeAssociateInputsToComponentStatus() {
1334         GraphVertex vertex = getTopologyTemplateVertex();
1335         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1336         when(topologyTemplateOperationMock.associateInputsToComponent(eq(vertex), anyMap(), anyString()))
1337             .thenReturn(StorageOperationStatus.NOT_FOUND);
1338         final var result = testInstance.createAndAssociateInputs(new HashMap<>(), COMPONENT_ID);
1339         assertTrue(result.isRight());
1340         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1341     }
1342
1343     @Test
1344     void testCreateAndAssociateInputs_componentNotFound() {
1345         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
1346         final var result = testInstance.createAndAssociateInputs(new HashMap<>(), COMPONENT_ID);
1347         assertTrue(result.isRight());
1348         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1349     }
1350
1351     @Test
1352     void testCreateAndAssociateOutputs_OK() {
1353         GraphVertex vertex = getTopologyTemplateVertex();
1354         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1355         when(topologyTemplateOperationMock.associateOutputsToComponent(eq(vertex), anyMap(), anyString())).thenReturn(StorageOperationStatus.OK);
1356         Map<String, OutputDefinition> outputs = new HashMap<>();
1357         outputs.put("1", new OutputDefinition());
1358         outputs.put("2", new OutputDefinition());
1359         final var result = testInstance.createAndAssociateOutputs(outputs, COMPONENT_ID);
1360         assertTrue(result.isLeft());
1361         assertNotNull(result.left());
1362         assertEquals(2, result.left().value().size());
1363     }
1364
1365     @Test
1366     void testCreateAndAssociateOutputs_NegativeAssociateOutputsToComponentStatus() {
1367         GraphVertex vertex = getTopologyTemplateVertex();
1368         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1369         when(topologyTemplateOperationMock.associateOutputsToComponent(eq(vertex), anyMap(), anyString()))
1370             .thenReturn(StorageOperationStatus.NOT_FOUND);
1371         final var result = testInstance.createAndAssociateOutputs(new HashMap<>(), COMPONENT_ID);
1372         assertTrue(result.isRight());
1373         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1374     }
1375
1376     @Test
1377     void testCreateAndAssociateOutputs_componentNotFound() {
1378         when(janusGraphDaoMock.getVertexById(COMPONENT_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
1379         final var result = testInstance.createAndAssociateOutputs(new HashMap<>(), COMPONENT_ID);
1380         assertTrue(result.isRight());
1381         assertEquals(StorageOperationStatus.NOT_FOUND, result.right().value());
1382     }
1383
1384     private StorageOperationStatus associateRequirementsToServiceWithStatus(StorageOperationStatus status) {
1385         Map<String, ListRequirementDataDefinition> requirementsMap = new HashedMap();
1386         String componentId = "componentid";
1387
1388         ListRequirementDataDefinition listRequirementDataDefinition1 = new ListRequirementDataDefinition();
1389         requirementsMap.put("requirements1", listRequirementDataDefinition1);
1390
1391         GraphVertex vertex;
1392         if (status == StorageOperationStatus.OK) {
1393             vertex = getTopologyTemplateVertex();
1394         } else {
1395             vertex = getNodeTypeVertex();
1396         }
1397
1398         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1399         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
1400         when(topologyTemplateOperationMock.associateElementToData(eq(vertex),
1401             eq(VertexTypeEnum.REQUIREMENTS), eq(EdgeLabelEnum.REQUIREMENTS), anyMap())).thenReturn(Either.right(status));
1402         return testInstance.associateRequirementsToService(requirementsMap, componentId);
1403     }
1404
1405     private Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponentWithStatus(StorageOperationStatus status) {
1406         PolicyDefinition policy = new PolicyDefinition();
1407         String componentId = "componentId";
1408         int counter = 0;
1409         GraphVertex vertex;
1410         if (status == StorageOperationStatus.OK) {
1411             vertex = getTopologyTemplateVertex();
1412         } else {
1413             vertex = getNodeTypeVertex();
1414         }
1415         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1416         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)).thenReturn(getVertexEither);
1417         if (status == StorageOperationStatus.OK) {
1418             when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status);
1419         }
1420         return testInstance.associatePolicyToComponent(componentId, policy, counter);
1421     }
1422
1423     private Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponentWithStatus(StorageOperationStatus status) {
1424         PolicyDefinition policy = new PolicyDefinition();
1425         String componentId = "componentId";
1426         GraphVertex vertex = getTopologyTemplateVertex();
1427         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(vertex));
1428         when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status);
1429         return testInstance.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.NONE);
1430     }
1431
1432     private void removePolicyFromComponentWithStatus(StorageOperationStatus status) {
1433         String componentId = "componentId";
1434         String policyId = "policyId";
1435         GraphVertex vertex = getTopologyTemplateVertex();
1436         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
1437         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
1438         when(topologyTemplateOperationMock.removePolicyFromToscaElement(vertex, policyId)).thenReturn(status);
1439         StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId);
1440         assertSame(result, status);
1441     }
1442
1443     private List<GraphVertex> getMockVertices(int numOfVertices) {
1444         return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList());
1445     }
1446
1447     private ToscaElement getResourceToscaElement(String id) {
1448         ToscaElement toscaElement = new TopologyTemplate();
1449         toscaElement.setMetadata(new HashMap<>());
1450         toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE");
1451         toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id);
1452         return toscaElement;
1453     }
1454
1455     private GraphVertex getTopologyTemplateVertex() {
1456         GraphVertex graphVertex = new GraphVertex();
1457         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1458         return graphVertex;
1459     }
1460
1461     private GraphVertex getNodeTypeVertex() {
1462         GraphVertex graphVertex = new GraphVertex();
1463         graphVertex.setLabel(VertexTypeEnum.NODE_TYPE);
1464         return graphVertex;
1465     }
1466
1467 }