Support for Nested/Hierarchical Services
[sdc.git] / catalog-model / src / test / java / org / openecomp / sdc / be / model / jsonjanusgraph / operations / ToscaOperationFacadeTest.java
1 /*
2
3  * Copyright (c) 2018 AT&T Intellectual Property.
4
5  *
6
7  * Licensed under the Apache License, Version 2.0 (the "License");
8
9  * you may not use this file except in compliance with the License.
10
11  * You may obtain a copy of the License at
12
13  *
14
15  *     http://www.apache.org/licenses/LICENSE-2.0
16
17  *
18
19  * Unless required by applicable law or agreed to in writing, software
20
21  * distributed under the License is distributed on an "AS IS" BASIS,
22
23  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
25  * See the License for the specific language governing permissions and
26
27  * limitations under the License.
28
29  */
30 package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
31
32 import fj.data.Either;
33 import org.apache.commons.lang3.tuple.ImmutablePair;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mockito.ArgumentCaptor;
38 import org.mockito.InjectMocks;
39 import org.mockito.Mock;
40 import org.mockito.ArgumentMatchers;
41 import org.mockito.MockitoAnnotations;
42 import org.mockito.junit.MockitoJUnitRunner;
43 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
44 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
45 import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
46 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
47 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
48 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
51 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
52 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
53 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
54 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.model.ComponentInstance;
57 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
58 import org.openecomp.sdc.be.model.Resource;
59 import org.openecomp.sdc.be.model.LifecycleStateEnum;
60 import org.openecomp.sdc.be.model.ComponentParametersView;
61 import org.openecomp.sdc.be.model.PolicyDefinition;
62 import org.openecomp.sdc.be.model.Service;
63 import org.openecomp.sdc.be.model.User;
64 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType;
65 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
66 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
67 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
68 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
69 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
70 import org.openecomp.sdc.be.model.DataTypeDefinition;
71 import org.openecomp.sdc.be.model.PropertyDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
73
74 import static org.assertj.core.api.Assertions.assertThat;
75
76 import java.util.HashMap;
77 import java.util.List;
78 import java.util.Map;
79 import java.util.ArrayList;
80 import java.util.EnumMap;
81 import java.util.Set;
82 import java.util.HashSet;
83 import java.util.stream.Collectors;
84 import java.util.stream.IntStream;
85 import java.util.Collections;
86 import java.util.Arrays;
87
88 import static org.junit.Assert.assertEquals;
89 import static org.junit.Assert.assertSame;
90 import static org.junit.Assert.assertTrue;
91 import static org.mockito.Mockito.times;
92 import static org.mockito.Mockito.verify;
93 import static org.mockito.Mockito.when;
94 import static org.mockito.ArgumentMatchers.any;
95 import static org.mockito.ArgumentMatchers.anyMap;
96 import static org.mockito.ArgumentMatchers.anyInt;
97 import static org.mockito.ArgumentMatchers.eq;
98
99 @RunWith(MockitoJUnitRunner.class)
100 public class ToscaOperationFacadeTest {
101     private static final String COMPONENT_ID = "componentId";
102     private static final String PROPERTY1_NAME = "prop1";
103     private static final String PROPERTY1_TYPE = "string";
104     private static final String PROPERTY2_NAME = "prop2";
105     private static final String PROPERTY2_TYPE = "integer";
106     private static final String ICON_NAME = "icon";
107     private static final String SERVICE_MODEL_NAME = "Test_Service";
108     private static final String SERVICE_PROXY_INSTANCE0_NAME = "testservice_proxy0";
109     private static final String SERVICE_SUBSTITUTION_INSTANCE0_NAME = "testservice0";
110
111     @InjectMocks
112     private ToscaOperationFacade testInstance;
113
114     @Mock
115     private HealingJanusGraphDao janusGraphDaoMock;
116
117     @Mock
118     private TopologyTemplateOperation topologyTemplateOperationMock;
119
120     @Mock
121     private NodeTypeOperation nodeTypeOperation;
122
123     @Mock
124     private NodeTemplateOperation nodeTemplateOperationMock;
125
126     @Before
127     public void setUp() throws Exception {
128         testInstance = new ToscaOperationFacade();
129         MockitoAnnotations.initMocks(this);
130     }
131
132     @SuppressWarnings("unchecked")
133     @Test
134     public void fetchMetaDataByResourceType() throws Exception {
135         ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class);
136         ArgumentCaptor<Map> criteriaNotCapture = ArgumentCaptor.forClass(Map.class);
137         ComponentParametersView dataFilter = new ComponentParametersView();
138         List<GraphVertex> mockVertices = getMockVertices(2);
139         Either<List<GraphVertex>, JanusGraphOperationStatus> returnedVertices = Either.left(mockVertices);
140
141         when(janusGraphDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices);
142         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0")));
143         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1")));
144         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter);
145
146         verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture);
147         verifyCriteriaNotIsDeleted(criteriaNotCapture);
148
149         assertTrue(fetchedComponents.isLeft());
150         List<Component> cmpts = fetchedComponents.left().value();
151         assertEquals(2, cmpts.size());
152         assertEquals("0", cmpts.get(0).getUniqueId());
153         assertEquals("1", cmpts.get(1).getUniqueId());
154     }
155
156     private void verifyCriteriaForHighestVersionAndVfResourceType(ArgumentCaptor<Map> criteriaCapture) {
157         Map<GraphPropertyEnum, Object> criteria = (Map<GraphPropertyEnum, Object>)criteriaCapture.getValue();
158         assertEquals(2, criteria.size());
159         assertEquals(criteria.get(GraphPropertyEnum.RESOURCE_TYPE), "VF");
160         assertEquals(criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION), true);
161     }
162
163     private void verifyCriteriaNotIsDeleted(ArgumentCaptor<Map> criteriaNotCapture) {
164         Map<GraphPropertyEnum, Object> notCriteria = (Map<GraphPropertyEnum, Object>)criteriaNotCapture.getValue();
165         assertEquals(1, notCriteria.size());
166         assertEquals(notCriteria.get(GraphPropertyEnum.IS_DELETED), true);
167     }
168
169     @SuppressWarnings("unchecked")
170     @Test
171     public void fetchMetaDataByResourceType_failedToGetData() throws Exception {
172         when(janusGraphDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(
173             JanusGraphOperationStatus.GENERAL_ERROR));
174         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView());
175         assertTrue(fetchedComponents.isRight());
176         assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value());
177     }
178
179     @Test
180     public void associatePolicyToComponentSuccessTest(){
181         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK);
182         assertTrue(result.isLeft());
183     }
184
185     @Test
186     public void associatePolicyToComponentFailureTest(){
187         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
188         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
189     }
190
191     @Test
192     public void updatePolicyOfComponentSuccessTest(){
193         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK);
194         assertTrue(result.isLeft());
195     }
196
197     @Test
198     public void updatePolicyOfComponentFailureTest(){
199         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND);
200         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
201     }
202
203     @Test
204     public void removePolicyFromComponentSuccessTest(){
205         removePolicyFromComponentWithStatus(StorageOperationStatus.OK);
206     }
207
208     @Test
209     public void removePolicyFromComponentFailureTest(){
210         removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND);
211     }
212
213     @Test
214     public void testFindLastCertifiedToscaElementByUUID(){
215         Either<Component, StorageOperationStatus> result;
216         Component component = new Resource();
217         List<GraphVertex> list = new ArrayList<>();
218         GraphVertex graphVertex = getTopologyTemplateVertex();
219         list.add(graphVertex);
220         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
221         props.put(GraphPropertyEnum.UUID, component.getUUID());
222         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
223         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
224         ToscaElement toscaElement = getToscaElementForTest();
225         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
226         when(janusGraphDaoMock.getByCriteria(ModelConverter.getVertexType(component), props)).thenReturn(Either.left(list));
227         result = testInstance.findLastCertifiedToscaElementByUUID(component);
228         Component resultComp = result.left().value();
229         assertEquals(resultComp.getToscaType(),ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
230     }
231
232     @Test
233     public void testLatestComponentByToscaResourceName(){
234         Either<Component, StorageOperationStatus> result;
235         TopologyTemplate toscaElement = new TopologyTemplate();
236         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
237         List<GraphVertex> list = new ArrayList<>();
238         GraphVertex graphVertex = getTopologyTemplateVertex();
239         Map<GraphPropertyEnum, Object> props = new HashMap<>();
240         props.put(GraphPropertyEnum.VERSION, "1.0");
241         graphVertex.setMetadataProperties(props);
242         list.add(graphVertex);
243
244         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
245         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
246         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "toscaResourceName");
247         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
248         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
249
250         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list));
251         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
252
253         result = testInstance.getFullLatestComponentByToscaResourceName("toscaResourceName");
254         assertThat(result.isLeft());
255     }
256
257     @Test
258     public void testValidateCsarUuidUniqueness() {
259         StorageOperationStatus result;
260         String csarUUID = "csarUUID";
261         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
262         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
263         List<GraphVertex> vertexList = new ArrayList<>();
264         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
265         result = testInstance.validateCsarUuidUniqueness(csarUUID);
266         assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, result);
267     }
268
269     @Test
270     public void testValidateCsarUuidUnique_true() {
271         StorageOperationStatus result;
272         String csarUUID = "csarUUID";
273         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
274         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
275         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
276             JanusGraphOperationStatus.NOT_FOUND));
277         result = testInstance.validateCsarUuidUniqueness(csarUUID);
278         assertEquals(StorageOperationStatus.OK, result);
279     }
280
281     @Test
282     public void testGetLatestCertiNodeTypeByToscaResourceName() {
283         Either<Resource, StorageOperationStatus> result;
284         String toscaResourceName = "resourceName";
285         String uniqueId = "uniqueId";
286         GraphVertex graphVertex = getTopologyTemplateVertex();
287         graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "1.0");
288         graphVertex.setUniqueId(uniqueId);
289         List<GraphVertex> vertexList = new ArrayList<>();
290         vertexList.add(graphVertex);
291         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
292         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
293         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
294         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
295         ToscaElement topologyTemplate = new TopologyTemplate();
296         topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE);
297         when(janusGraphDaoMock.getByCriteria(VertexTypeEnum.NODE_TYPE, props, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
298         when(janusGraphDaoMock.getVertexById(uniqueId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
299         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(topologyTemplate));
300         result = testInstance.getLatestCertifiedNodeTypeByToscaResourceName(toscaResourceName);
301         assertThat(result.isLeft());
302     }
303
304     @Test
305     public void testValidateCompExists() {
306         Either<Boolean, StorageOperationStatus> result;
307         String componentId = "componentId";
308         GraphVertex graphVertex = getTopologyTemplateVertex();
309         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
310         result = testInstance.validateComponentExists(componentId);
311         assertEquals(true, result.left().value());
312     }
313
314     @Test
315     public void testValidateCompExists_NotFound() {
316         Either<Boolean, StorageOperationStatus> result;
317         String componentId = "componentId";
318         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
319             JanusGraphOperationStatus.NOT_FOUND));
320         result = testInstance.validateComponentExists(componentId);
321         assertEquals(false, result.left().value());
322     }
323
324     @Test
325     public void testValidateToscaResourceNameExists() {
326         Either<Boolean, StorageOperationStatus> result;
327         String templateName = "templateName";
328         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
329         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
330         List<GraphVertex> graphVertexList = new ArrayList<>();
331         GraphVertex graphVertex = getTopologyTemplateVertex();
332         graphVertexList.add(graphVertex);
333         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList));
334         result = testInstance.validateToscaResourceNameExists(templateName);
335         assertEquals(true, result.left().value());
336     }
337
338     @Test
339     public void testValidateToscaResourceNameExists_false() {
340         Either<Boolean, StorageOperationStatus> result;
341         String templateName = "templateName";
342         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
343         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
344         List<GraphVertex> graphVertexList = new ArrayList<>();
345         GraphVertex graphVertex = getTopologyTemplateVertex();
346         graphVertexList.add(graphVertex);
347         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
348             JanusGraphOperationStatus.NOT_FOUND));
349         result = testInstance.validateToscaResourceNameExists(templateName);
350         assertEquals(false, result.left().value());
351     }
352
353     @Test
354     public void testOverrideComponent() {
355         Either<Resource, StorageOperationStatus> result;
356         Resource resource = new Resource();
357         String id = "id";
358         resource.setUniqueId(id);
359         GraphVertex graphVertex = getTopologyTemplateVertex();
360         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
361         NodeType nodeType = new NodeType();
362         nodeType.setComponentType(ComponentTypeEnum.RESOURCE);
363         ToscaElement toscaElement = new TopologyTemplate();
364         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
365         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
366         when(janusGraphDaoMock.getParentVertex(graphVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
367         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
368         when(nodeTypeOperation.createToscaElement(any(ToscaElement.class))).thenReturn(Either.left(nodeType));
369         when(janusGraphDaoMock.getVertexById(null, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
370         when(janusGraphDaoMock.createEdge(graphVertex, graphVertex, EdgeLabelEnum.VERSION, null)).thenReturn(
371             JanusGraphOperationStatus.OK);
372         result = testInstance.overrideComponent(resource, resource);
373         assertTrue(result.isLeft());
374     }
375
376     @Test
377     public void testGetToscaElement() {
378         Either<Component, StorageOperationStatus> result;
379         String id = "id";
380         GraphVertex graphVertex = getTopologyTemplateVertex();
381         ToscaElement toscaElement = getToscaElementForTest();
382         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
383         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
384         result = testInstance.getToscaElement(id, JsonParseFlagEnum.ParseAll);
385         assertTrue(result.isLeft());
386     }
387
388     @Test
389     public void testMarkComponentToDelete() {
390         StorageOperationStatus result;
391         Component component = new Resource();
392         String id = "id";
393         component.setUniqueId(id);
394         GraphVertex graphVertex = getTopologyTemplateVertex();
395         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
396         when(nodeTypeOperation.markComponentToDelete(graphVertex)).thenReturn(Either.left(graphVertex));
397         result = testInstance.markComponentToDelete(component);
398         assertEquals(result, StorageOperationStatus.OK);
399     }
400
401     @Test
402     public void testDelToscaComponent() {
403         Either<Component, StorageOperationStatus> result;
404         String componentId = "compId";
405         GraphVertex graphVertex = getTopologyTemplateVertex();
406         ToscaElement toscaElement = getToscaElementForTest();
407         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
408         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
409         result = testInstance.deleteToscaComponent(componentId);
410         assertTrue(result.isLeft());
411     }
412
413     @Test
414     public void testGetLatestByToscaResourceName() {
415         Either<Component, StorageOperationStatus> result;
416         String toscaResourceName = "name";
417         ToscaElement toscaElement = getToscaElementForTest();
418
419         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
420         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
421         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
422         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
423         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
424
425         List<GraphVertex> graphVertexList = new ArrayList<>();
426         GraphVertex graphVertex = getTopologyTemplateVertex();
427         graphVertex.setUniqueId(toscaResourceName);
428         Map<GraphPropertyEnum, Object> props = new HashMap<>();
429         props.put(GraphPropertyEnum.VERSION, "1.0");
430         graphVertex.setMetadataProperties(props);
431         graphVertexList.add(graphVertex);
432
433         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList));
434         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
435         result = testInstance.getLatestByToscaResourceName(toscaResourceName);
436         assertTrue(result.isLeft());
437     }
438
439     @Test
440     public void testGetFollowed() {
441         Either<Set<Component>, StorageOperationStatus> result;
442         String userId = "id";
443         Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
444         Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
445         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
446         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
447         lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
448         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
449         List<ToscaElement> toscaEleList = new ArrayList<>();
450         ToscaElement toscaElement = getToscaElementForTest();
451         toscaEleList.add(toscaElement);
452         when(nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType)).thenReturn(Either.left(toscaEleList));
453         result = testInstance.getFollowed(userId, lifecycleStates, lastStateStates, componentType);
454         assertTrue(result.isLeft());
455         assertEquals(1, result.left().value().size());
456     }
457
458     @Test
459     public void testGetBySystemName() {
460         Either<List<Component>, StorageOperationStatus> result;
461         String sysName = "sysName";
462         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
463         ToscaElement toscaElement = getToscaElementForTest();
464         List<GraphVertex> componentVertices = new ArrayList<>();
465         GraphVertex graphVertex = getTopologyTemplateVertex();
466         componentVertices.add(graphVertex);
467         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
468         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
469
470         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName);
471         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name());
472
473         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
474
475         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(componentVertices));
476         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
477         result = testInstance.getBySystemName(componentTypeEnum, sysName);
478         assertTrue(result.isLeft());
479         assertEquals(1, result.left().value().size());
480     }
481
482     @Test
483     public void testGetCompByNameAndVersion() {
484         Either<Component, StorageOperationStatus> result;
485         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
486         String name = "name";
487         String version = "1.0";
488         JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll;
489         List<GraphVertex> graphVertexList = new ArrayList<>();
490         GraphVertex graphVertex = getTopologyTemplateVertex();
491         graphVertexList.add(graphVertex);
492         ToscaElement toscaElement = getToscaElementForTest();
493         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
494         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
495
496         hasProperties.put(GraphPropertyEnum.NAME, name);
497         hasProperties.put(GraphPropertyEnum.VERSION, version);
498         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
499         hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
500         when(janusGraphDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList));
501         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
502         result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag);
503         assertTrue(result.isLeft());
504     }
505
506     private ToscaElement getToscaElementForTest() {
507         ToscaElement toscaElement = new TopologyTemplate();
508         toscaElement.setComponentType(ComponentTypeEnum.RESOURCE);
509         return toscaElement;
510     }
511
512     @Test
513     public void addDataTypesToComponentSuccessTest(){
514         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK);
515         assertTrue(result.isLeft());
516     }
517
518     @Test
519     public void addDataTypesToComponentFailureTest_BadRequest(){
520         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
521         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
522     }
523
524     private Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) {
525         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
526         String componentId = "componentid";
527         String Id = "id";
528
529         PropertyDefinition noDefaultProp = new PropertyDefinition();
530         noDefaultProp.setName("noDefaultProp");
531         PropertyDefinition prop1 = new PropertyDefinition();
532         prop1.setDefaultValue("def1");
533         prop1.setName("prop1");
534         PropertyDefinition prop2 = new PropertyDefinition();
535         prop2.setType("dataType1");
536         prop2.setName("prop2");
537         PropertyDefinition prop3 = new PropertyDefinition();
538         prop3.setDefaultValue("def3");
539         prop3.setName("prop3");
540
541         DataTypeDefinition noDefaultValue = new DataTypeDefinition();
542         noDefaultValue.setProperties(Collections.singletonList(noDefaultProp));
543         noDefaultValue.setDerivedFromName("name0");
544
545         DataTypeDefinition dataType1 = new DataTypeDefinition();
546         dataType1.setProperties(Arrays.asList(prop1, prop3));
547         dataType1.setName("name1");
548         dataType1.setDerivedFromName("derivedfromname1");
549
550         DataTypeDefinition dataType2 = new DataTypeDefinition();
551         dataType2.setDerivedFrom(dataType1);
552         dataType2.setName("name2");
553         dataType2.setDerivedFromName("derivedfromname2");
554
555         DataTypeDefinition dataType3 = new DataTypeDefinition();
556         dataType3.setProperties(Collections.singletonList(prop2));
557         dataType3.setDerivedFrom(noDefaultValue);
558         dataType3.setName("name3");
559         dataType3.setDerivedFromName("derivedfromname3");
560
561         dataTypes.put("noDefault", noDefaultValue);
562         dataTypes.put("dataType1", dataType1);
563         dataTypes.put("dataType2", dataType2);
564         dataTypes.put("dataType3", dataType3);
565
566         GraphVertex vertex;
567         if(status == StorageOperationStatus.OK){
568             vertex = getTopologyTemplateVertex();
569         } else {
570             vertex = getNodeTypeVertex();
571         }
572         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
573         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
574         when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex),
575                 eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status);
576         return testInstance.addDataTypesToComponent(dataTypes, componentId);
577     }
578
579     @Test
580     public void testDataTypesToComponentFailureTest_NotFound() {
581         Either<List<DataTypeDefinition>, StorageOperationStatus> result;
582         String componentId = "componentId";
583         GraphVertex vertex = getNodeTypeVertex();
584         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
585         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
586             JanusGraphOperationStatus.NOT_FOUND));
587         result = testInstance.addDataTypesToComponent(dataTypes, componentId);
588         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
589     }
590
591     @Test
592     public void testDeleteDataTypeOfComponent() {
593         StorageOperationStatus result;
594         Component component = new Resource();
595         String id = "id";
596         component.setUniqueId(id);
597         String datatype = null;
598
599         DataTypeDefinition dataType1 = new DataTypeDefinition();
600         dataType1.setName("name1");
601         Map<String, DataTypeDataDefinition> dataTypeDataMap = new HashMap<>();
602         dataTypeDataMap.put("datatype1", dataType1);
603         List<DataTypeDefinition> dataTypeMap = dataTypeDataMap.values().stream().map(e -> { DataTypeDefinition dataType = new DataTypeDefinition(e);return dataType; }).collect(Collectors.toList());
604         component.setDataTypes(dataTypeMap);
605         GraphVertex graphVertex = getTopologyTemplateVertex();
606         result = testInstance.deleteDataTypeOfComponent(component, "datatype1");
607         assertEquals(datatype, result);
608     }
609
610     @Test
611     public void testAddComponentInstancePropertiesToComponent() {
612         // set up component object
613         Component component = new Resource();
614         component.setUniqueId(COMPONENT_ID);
615         List<ComponentInstanceProperty> instanceProps = new ArrayList<>();
616         ComponentInstanceProperty instanceProp = new ComponentInstanceProperty();
617         instanceProp.setName(PROPERTY1_NAME);
618         instanceProp.setType(PROPERTY1_TYPE);
619         instanceProps.add(instanceProp);
620         instanceProp = new ComponentInstanceProperty();
621         instanceProp.setName(PROPERTY2_NAME);
622         instanceProp.setType(PROPERTY2_TYPE);
623         instanceProps.add(instanceProp);
624         Map<String, List<ComponentInstanceProperty>> instancePropsMap =
625             Collections.singletonMap(COMPONENT_ID, instanceProps);
626         component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>()));
627
628         when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any()))
629             .thenReturn(StorageOperationStatus.OK);
630
631         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> result =
632             testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap);
633         assertTrue(result.isLeft());
634         verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any());
635         List<ComponentInstanceProperty> resultProps = result.left().value().get(COMPONENT_ID);
636         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME)));
637         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME)));
638     }
639
640     @Test
641     public void testAddComponentInstanceToTopologyTemplate_ServiceProxy() {
642         Component containerComponent = new Service();
643         Component originalComponent = new Service();
644         ComponentInstance componentInstance = new ComponentInstance();
645         ComponentInstance existingComponentInstance = new ComponentInstance();
646         User user = new User();
647
648         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
649
650         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
651         originalComponent.setIcon(ICON_NAME);
652
653         componentInstance.setOriginType(OriginTypeEnum.ServiceProxy);
654         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
655
656         List<ComponentInstance> existingInstances = new ArrayList<>();
657         existingComponentInstance.setNormalizedName(SERVICE_PROXY_INSTANCE0_NAME);
658         existingInstances.add(existingComponentInstance);
659         containerComponent.setComponentInstances(existingInstances);
660
661         when(nodeTemplateOperationMock
662             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
663             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
664         TopologyTemplate topologyTemplate = new TopologyTemplate();
665         // preset COMPONENT_TYPE field for internal ModelConverter call
666         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
667         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
668             .thenReturn(Either.left(topologyTemplate));
669
670         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
671             testInstance.addComponentInstanceToTopologyTemplate(
672                 containerComponent, originalComponent, componentInstance, false, user);
673
674         assertTrue(result.isLeft());
675         assertEquals(componentInstance.getIcon(), ICON_NAME);
676         assertEquals(result.left().value().getRight(), COMPONENT_ID);
677         // the instance counter must be 1 because the service proxy instance with suffix 0 already exists.
678         verify(nodeTemplateOperationMock, times(1))
679             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
680     }
681     @Test
682     public void testAddComponentInstanceToTopologyTemplate_ServiceSubstitution() {
683         Component containerComponent = new Service();
684         Component originalComponent = new Service();
685         ComponentInstance componentInstance = new ComponentInstance();
686         ComponentInstance existingComponentInstance = new ComponentInstance();
687         User user = new User();
688
689         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
690
691         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
692         originalComponent.setIcon(ICON_NAME);
693
694         componentInstance.setOriginType(OriginTypeEnum.ServiceSubstitution);
695         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
696
697         List<ComponentInstance> existingInstances = new ArrayList<>();
698         existingComponentInstance.setNormalizedName(SERVICE_SUBSTITUTION_INSTANCE0_NAME);
699         existingInstances.add(existingComponentInstance);
700         containerComponent.setComponentInstances(existingInstances);
701
702         when(nodeTemplateOperationMock
703             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
704             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
705         TopologyTemplate topologyTemplate = new TopologyTemplate();
706         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
707         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
708             .thenReturn(Either.left(topologyTemplate));
709
710         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
711             testInstance.addComponentInstanceToTopologyTemplate(
712                 containerComponent, originalComponent, componentInstance, false, user);
713
714         assertTrue(result.isLeft());
715         assertEquals(ICON_NAME, componentInstance.getIcon());
716         assertEquals(COMPONENT_ID, result.left().value().getRight());
717         verify(nodeTemplateOperationMock, times(1))
718             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
719     }
720
721     private Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponentWithStatus(StorageOperationStatus status) {
722         PolicyDefinition policy = new PolicyDefinition();
723         String componentId = "componentId";
724         int counter = 0;
725         GraphVertex vertex;
726         if(status == StorageOperationStatus.OK){
727             vertex = getTopologyTemplateVertex();
728         } else {
729             vertex = getNodeTypeVertex();
730         }
731         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
732         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither);
733         when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status);
734         return testInstance.associatePolicyToComponent(componentId, policy, counter);
735     }
736
737     private Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponentWithStatus(StorageOperationStatus status) {
738         PolicyDefinition policy = new PolicyDefinition();
739         String componentId = "componentId";
740         GraphVertex vertex = getTopologyTemplateVertex();
741         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex));
742         when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status);
743         return testInstance.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.NONE);
744     }
745
746     private void removePolicyFromComponentWithStatus(StorageOperationStatus status) {
747         String componentId = "componentId";
748         String policyId = "policyId";
749         GraphVertex vertex = getTopologyTemplateVertex();
750         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
751         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither);
752         when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status);
753         StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId);
754         assertSame(result, status);
755     }
756
757     private List<GraphVertex> getMockVertices(int numOfVertices) {
758         return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList());
759     }
760
761     private ToscaElement getResourceToscaElement(String id) {
762         ToscaElement toscaElement = new TopologyTemplate();
763         toscaElement.setMetadata(new HashMap<>());
764         toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE");
765         toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id);
766         return toscaElement;
767     }
768
769     private GraphVertex getTopologyTemplateVertex() {
770         GraphVertex graphVertex = new GraphVertex();
771         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
772         return graphVertex;
773     }
774
775     private GraphVertex getNodeTypeVertex() {
776         GraphVertex graphVertex = new GraphVertex();
777         graphVertex.setLabel(VertexTypeEnum.NODE_TYPE);
778         return graphVertex;
779     }
780 }