caf1805b8396166b8ebbc7600c12d5bbf6349231
[sdc.git] /
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
110     @InjectMocks
111     private ToscaOperationFacade testInstance;
112
113     @Mock
114     private HealingJanusGraphDao janusGraphDaoMock;
115
116     @Mock
117     private TopologyTemplateOperation topologyTemplateOperationMock;
118
119     @Mock
120     private NodeTypeOperation nodeTypeOperation;
121
122     @Mock
123     private NodeTemplateOperation nodeTemplateOperationMock;
124
125     @Before
126     public void setUp() throws Exception {
127         testInstance = new ToscaOperationFacade();
128         MockitoAnnotations.initMocks(this);
129     }
130
131     @SuppressWarnings("unchecked")
132     @Test
133     public void fetchMetaDataByResourceType() throws Exception {
134         ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class);
135         ArgumentCaptor<Map> criteriaNotCapture = ArgumentCaptor.forClass(Map.class);
136         ComponentParametersView dataFilter = new ComponentParametersView();
137         List<GraphVertex> mockVertices = getMockVertices(2);
138         Either<List<GraphVertex>, JanusGraphOperationStatus> returnedVertices = Either.left(mockVertices);
139
140         when(janusGraphDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices);
141         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0")));
142         when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1")));
143         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter);
144
145         verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture);
146         verifyCriteriaNotIsDeleted(criteriaNotCapture);
147
148         assertTrue(fetchedComponents.isLeft());
149         List<Component> cmpts = fetchedComponents.left().value();
150         assertEquals(2, cmpts.size());
151         assertEquals("0", cmpts.get(0).getUniqueId());
152         assertEquals("1", cmpts.get(1).getUniqueId());
153     }
154
155     private void verifyCriteriaForHighestVersionAndVfResourceType(ArgumentCaptor<Map> criteriaCapture) {
156         Map<GraphPropertyEnum, Object> criteria = (Map<GraphPropertyEnum, Object>)criteriaCapture.getValue();
157         assertEquals(2, criteria.size());
158         assertEquals(criteria.get(GraphPropertyEnum.RESOURCE_TYPE), "VF");
159         assertEquals(criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION), true);
160     }
161
162     private void verifyCriteriaNotIsDeleted(ArgumentCaptor<Map> criteriaNotCapture) {
163         Map<GraphPropertyEnum, Object> notCriteria = (Map<GraphPropertyEnum, Object>)criteriaNotCapture.getValue();
164         assertEquals(1, notCriteria.size());
165         assertEquals(notCriteria.get(GraphPropertyEnum.IS_DELETED), true);
166     }
167
168     @SuppressWarnings("unchecked")
169     @Test
170     public void fetchMetaDataByResourceType_failedToGetData() throws Exception {
171         when(janusGraphDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(
172             JanusGraphOperationStatus.GENERAL_ERROR));
173         Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView());
174         assertTrue(fetchedComponents.isRight());
175         assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value());
176     }
177
178     @Test
179     public void associatePolicyToComponentSuccessTest(){
180         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK);
181         assertTrue(result.isLeft());
182     }
183
184     @Test
185     public void associatePolicyToComponentFailureTest(){
186         Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
187         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
188     }
189
190     @Test
191     public void updatePolicyOfComponentSuccessTest(){
192         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK);
193         assertTrue(result.isLeft());
194     }
195
196     @Test
197     public void updatePolicyOfComponentFailureTest(){
198         Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND);
199         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
200     }
201
202     @Test
203     public void removePolicyFromComponentSuccessTest(){
204         removePolicyFromComponentWithStatus(StorageOperationStatus.OK);
205     }
206
207     @Test
208     public void removePolicyFromComponentFailureTest(){
209         removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND);
210     }
211
212     @Test
213     public void testFindLastCertifiedToscaElementByUUID(){
214         Either<Component, StorageOperationStatus> result;
215         Component component = new Resource();
216         List<GraphVertex> list = new ArrayList<>();
217         GraphVertex graphVertex = getTopologyTemplateVertex();
218         list.add(graphVertex);
219         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
220         props.put(GraphPropertyEnum.UUID, component.getUUID());
221         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
222         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
223         ToscaElement toscaElement = getToscaElementForTest();
224         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
225         when(janusGraphDaoMock.getByCriteria(ModelConverter.getVertexType(component), props)).thenReturn(Either.left(list));
226         result = testInstance.findLastCertifiedToscaElementByUUID(component);
227         Component resultComp = result.left().value();
228         assertEquals(resultComp.getToscaType(),ToscaElementTypeEnum.TOPOLOGY_TEMPLATE.getValue());
229     }
230
231     @Test
232     public void testLatestComponentByToscaResourceName(){
233         Either<Component, StorageOperationStatus> result;
234         TopologyTemplate toscaElement = new TopologyTemplate();
235         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
236         List<GraphVertex> list = new ArrayList<>();
237         GraphVertex graphVertex = getTopologyTemplateVertex();
238         Map<GraphPropertyEnum, Object> props = new HashMap<>();
239         props.put(GraphPropertyEnum.VERSION, "1.0");
240         graphVertex.setMetadataProperties(props);
241         list.add(graphVertex);
242
243         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
244         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
245         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "toscaResourceName");
246         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
247         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
248
249         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(list));
250         when(topologyTemplateOperationMock.getToscaElement(ArgumentMatchers.eq(graphVertex),any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
251
252         result = testInstance.getFullLatestComponentByToscaResourceName("toscaResourceName");
253         assertThat(result.isLeft());
254     }
255
256     @Test
257     public void testValidateCsarUuidUniqueness() {
258         StorageOperationStatus result;
259         String csarUUID = "csarUUID";
260         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
261         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
262         List<GraphVertex> vertexList = new ArrayList<>();
263         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
264         result = testInstance.validateCsarUuidUniqueness(csarUUID);
265         assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, result);
266     }
267
268     @Test
269     public void testValidateCsarUuidUnique_true() {
270         StorageOperationStatus result;
271         String csarUUID = "csarUUID";
272         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
273         properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
274         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
275             JanusGraphOperationStatus.NOT_FOUND));
276         result = testInstance.validateCsarUuidUniqueness(csarUUID);
277         assertEquals(StorageOperationStatus.OK, result);
278     }
279
280     @Test
281     public void testGetLatestCertiNodeTypeByToscaResourceName() {
282         Either<Resource, StorageOperationStatus> result;
283         String toscaResourceName = "resourceName";
284         String uniqueId = "uniqueId";
285         GraphVertex graphVertex = getTopologyTemplateVertex();
286         graphVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "1.0");
287         graphVertex.setUniqueId(uniqueId);
288         List<GraphVertex> vertexList = new ArrayList<>();
289         vertexList.add(graphVertex);
290         Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
291         props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
292         props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
293         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
294         ToscaElement topologyTemplate = new TopologyTemplate();
295         topologyTemplate.setComponentType(ComponentTypeEnum.SERVICE);
296         when(janusGraphDaoMock.getByCriteria(VertexTypeEnum.NODE_TYPE, props, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(vertexList));
297         when(janusGraphDaoMock.getVertexById(uniqueId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
298         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(topologyTemplate));
299         result = testInstance.getLatestCertifiedNodeTypeByToscaResourceName(toscaResourceName);
300         assertThat(result.isLeft());
301     }
302
303     @Test
304     public void testValidateCompExists() {
305         Either<Boolean, StorageOperationStatus> result;
306         String componentId = "componentId";
307         GraphVertex graphVertex = getTopologyTemplateVertex();
308         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
309         result = testInstance.validateComponentExists(componentId);
310         assertEquals(true, result.left().value());
311     }
312
313     @Test
314     public void testValidateCompExists_NotFound() {
315         Either<Boolean, StorageOperationStatus> result;
316         String componentId = "componentId";
317         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
318             JanusGraphOperationStatus.NOT_FOUND));
319         result = testInstance.validateComponentExists(componentId);
320         assertEquals(false, result.left().value());
321     }
322
323     @Test
324     public void testValidateToscaResourceNameExists() {
325         Either<Boolean, StorageOperationStatus> result;
326         String templateName = "templateName";
327         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
328         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
329         List<GraphVertex> graphVertexList = new ArrayList<>();
330         GraphVertex graphVertex = getTopologyTemplateVertex();
331         graphVertexList.add(graphVertex);
332         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList));
333         result = testInstance.validateToscaResourceNameExists(templateName);
334         assertEquals(true, result.left().value());
335     }
336
337     @Test
338     public void testValidateToscaResourceNameExists_false() {
339         Either<Boolean, StorageOperationStatus> result;
340         String templateName = "templateName";
341         Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
342         properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, templateName);
343         List<GraphVertex> graphVertexList = new ArrayList<>();
344         GraphVertex graphVertex = getTopologyTemplateVertex();
345         graphVertexList.add(graphVertex);
346         when(janusGraphDaoMock.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.right(
347             JanusGraphOperationStatus.NOT_FOUND));
348         result = testInstance.validateToscaResourceNameExists(templateName);
349         assertEquals(false, result.left().value());
350     }
351
352     @Test
353     public void testOverrideComponent() {
354         Either<Resource, StorageOperationStatus> result;
355         Resource resource = new Resource();
356         String id = "id";
357         resource.setUniqueId(id);
358         GraphVertex graphVertex = getTopologyTemplateVertex();
359         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
360         NodeType nodeType = new NodeType();
361         nodeType.setComponentType(ComponentTypeEnum.RESOURCE);
362         ToscaElement toscaElement = new TopologyTemplate();
363         toscaElement.setComponentType(ComponentTypeEnum.SERVICE);
364         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
365         when(janusGraphDaoMock.getParentVertex(graphVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
366         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
367         when(nodeTypeOperation.createToscaElement(any(ToscaElement.class))).thenReturn(Either.left(nodeType));
368         when(janusGraphDaoMock.getVertexById(null, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(graphVertex));
369         when(janusGraphDaoMock.createEdge(graphVertex, graphVertex, EdgeLabelEnum.VERSION, null)).thenReturn(
370             JanusGraphOperationStatus.OK);
371         result = testInstance.overrideComponent(resource, resource);
372         assertTrue(result.isLeft());
373     }
374
375     @Test
376     public void testGetToscaElement() {
377         Either<Component, StorageOperationStatus> result;
378         String id = "id";
379         GraphVertex graphVertex = getTopologyTemplateVertex();
380         ToscaElement toscaElement = getToscaElementForTest();
381         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
382         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
383         result = testInstance.getToscaElement(id, JsonParseFlagEnum.ParseAll);
384         assertTrue(result.isLeft());
385     }
386
387     @Test
388     public void testMarkComponentToDelete() {
389         StorageOperationStatus result;
390         Component component = new Resource();
391         String id = "id";
392         component.setUniqueId(id);
393         GraphVertex graphVertex = getTopologyTemplateVertex();
394         when(janusGraphDaoMock.getVertexById(id, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
395         when(nodeTypeOperation.markComponentToDelete(graphVertex)).thenReturn(Either.left(graphVertex));
396         result = testInstance.markComponentToDelete(component);
397         assertEquals(result, StorageOperationStatus.OK);
398     }
399
400     @Test
401     public void testDelToscaComponent() {
402         Either<Component, StorageOperationStatus> result;
403         String componentId = "compId";
404         GraphVertex graphVertex = getTopologyTemplateVertex();
405         ToscaElement toscaElement = getToscaElementForTest();
406         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(graphVertex));
407         when(topologyTemplateOperationMock.deleteToscaElement(graphVertex)).thenReturn(Either.left(toscaElement));
408         result = testInstance.deleteToscaComponent(componentId);
409         assertTrue(result.isLeft());
410     }
411
412     @Test
413     public void testGetLatestByToscaResourceName() {
414         Either<Component, StorageOperationStatus> result;
415         String toscaResourceName = "name";
416         ToscaElement toscaElement = getToscaElementForTest();
417
418         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
419         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
420         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
421         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
422         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
423
424         List<GraphVertex> graphVertexList = new ArrayList<>();
425         GraphVertex graphVertex = getTopologyTemplateVertex();
426         graphVertex.setUniqueId(toscaResourceName);
427         Map<GraphPropertyEnum, Object> props = new HashMap<>();
428         props.put(GraphPropertyEnum.VERSION, "1.0");
429         graphVertex.setMetadataProperties(props);
430         graphVertexList.add(graphVertex);
431
432         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata)).thenReturn(Either.left(graphVertexList));
433         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
434         result = testInstance.getLatestByToscaResourceName(toscaResourceName);
435         assertTrue(result.isLeft());
436     }
437
438     @Test
439     public void testGetFollowed() {
440         Either<Set<Component>, StorageOperationStatus> result;
441         String userId = "id";
442         Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
443         Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
444         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
445         lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
446         lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
447         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
448         List<ToscaElement> toscaEleList = new ArrayList<>();
449         ToscaElement toscaElement = getToscaElementForTest();
450         toscaEleList.add(toscaElement);
451         when(nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType)).thenReturn(Either.left(toscaEleList));
452         result = testInstance.getFollowed(userId, lifecycleStates, lastStateStates, componentType);
453         assertTrue(result.isLeft());
454         assertEquals(1, result.left().value().size());
455     }
456
457     @Test
458     public void testGetBySystemName() {
459         Either<List<Component>, StorageOperationStatus> result;
460         String sysName = "sysName";
461         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.RESOURCE;
462         ToscaElement toscaElement = getToscaElementForTest();
463         List<GraphVertex> componentVertices = new ArrayList<>();
464         GraphVertex graphVertex = getTopologyTemplateVertex();
465         componentVertices.add(graphVertex);
466         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
467         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
468
469         propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, sysName);
470         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentTypeEnum.name());
471
472         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
473
474         when(janusGraphDaoMock.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)).thenReturn(Either.left(componentVertices));
475         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
476         result = testInstance.getBySystemName(componentTypeEnum, sysName);
477         assertTrue(result.isLeft());
478         assertEquals(1, result.left().value().size());
479     }
480
481     @Test
482     public void testGetCompByNameAndVersion() {
483         Either<Component, StorageOperationStatus> result;
484         ComponentTypeEnum componentType = ComponentTypeEnum.RESOURCE;
485         String name = "name";
486         String version = "1.0";
487         JsonParseFlagEnum parseFlag = JsonParseFlagEnum.ParseAll;
488         List<GraphVertex> graphVertexList = new ArrayList<>();
489         GraphVertex graphVertex = getTopologyTemplateVertex();
490         graphVertexList.add(graphVertex);
491         ToscaElement toscaElement = getToscaElementForTest();
492         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
493         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
494
495         hasProperties.put(GraphPropertyEnum.NAME, name);
496         hasProperties.put(GraphPropertyEnum.VERSION, version);
497         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
498         hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
499         when(janusGraphDaoMock.getByCriteria(null, hasProperties, hasNotProperties, parseFlag)).thenReturn(Either.left(graphVertexList));
500         when(topologyTemplateOperationMock.getToscaElement(any(GraphVertex.class), any(ComponentParametersView.class))).thenReturn(Either.left(toscaElement));
501         result = testInstance.getComponentByNameAndVersion(componentType, name, version, parseFlag);
502         assertTrue(result.isLeft());
503     }
504
505     private ToscaElement getToscaElementForTest() {
506         ToscaElement toscaElement = new TopologyTemplate();
507         toscaElement.setComponentType(ComponentTypeEnum.RESOURCE);
508         return toscaElement;
509     }
510
511     @Test
512     public void addDataTypesToComponentSuccessTest(){
513         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.OK);
514         assertTrue(result.isLeft());
515     }
516
517     @Test
518     public void addDataTypesToComponentFailureTest_BadRequest(){
519         Either<List<DataTypeDefinition>, StorageOperationStatus> result = addDataTypesToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
520         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
521     }
522
523     private Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponentWithStatus(StorageOperationStatus status) {
524         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
525         String componentId = "componentid";
526         String Id = "id";
527
528         PropertyDefinition noDefaultProp = new PropertyDefinition();
529         noDefaultProp.setName("noDefaultProp");
530         PropertyDefinition prop1 = new PropertyDefinition();
531         prop1.setDefaultValue("def1");
532         prop1.setName("prop1");
533         PropertyDefinition prop2 = new PropertyDefinition();
534         prop2.setType("dataType1");
535         prop2.setName("prop2");
536         PropertyDefinition prop3 = new PropertyDefinition();
537         prop3.setDefaultValue("def3");
538         prop3.setName("prop3");
539
540         DataTypeDefinition noDefaultValue = new DataTypeDefinition();
541         noDefaultValue.setProperties(Collections.singletonList(noDefaultProp));
542         noDefaultValue.setDerivedFromName("name0");
543
544         DataTypeDefinition dataType1 = new DataTypeDefinition();
545         dataType1.setProperties(Arrays.asList(prop1, prop3));
546         dataType1.setName("name1");
547         dataType1.setDerivedFromName("derivedfromname1");
548
549         DataTypeDefinition dataType2 = new DataTypeDefinition();
550         dataType2.setDerivedFrom(dataType1);
551         dataType2.setName("name2");
552         dataType2.setDerivedFromName("derivedfromname2");
553
554         DataTypeDefinition dataType3 = new DataTypeDefinition();
555         dataType3.setProperties(Collections.singletonList(prop2));
556         dataType3.setDerivedFrom(noDefaultValue);
557         dataType3.setName("name3");
558         dataType3.setDerivedFromName("derivedfromname3");
559
560         dataTypes.put("noDefault", noDefaultValue);
561         dataTypes.put("dataType1", dataType1);
562         dataTypes.put("dataType2", dataType2);
563         dataTypes.put("dataType3", dataType3);
564
565         GraphVertex vertex;
566         if(status == StorageOperationStatus.OK){
567             vertex = getTopologyTemplateVertex();
568         } else {
569             vertex = getNodeTypeVertex();
570         }
571         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
572         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(getVertexEither);
573         when(topologyTemplateOperationMock.addToscaDataToToscaElement(eq(vertex),
574                 eq(EdgeLabelEnum.DATA_TYPES), eq(VertexTypeEnum.DATA_TYPES), anyMap(), eq(JsonPresentationFields.NAME))).thenReturn(status);
575         return testInstance.addDataTypesToComponent(dataTypes, componentId);
576     }
577
578     @Test
579     public void testDataTypesToComponentFailureTest_NotFound() {
580         Either<List<DataTypeDefinition>, StorageOperationStatus> result;
581         String componentId = "componentId";
582         GraphVertex vertex = getNodeTypeVertex();
583         Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
584         when(janusGraphDaoMock.getVertexById(componentId, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(
585             JanusGraphOperationStatus.NOT_FOUND));
586         result = testInstance.addDataTypesToComponent(dataTypes, componentId);
587         assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
588     }
589
590     @Test
591     public void testDeleteDataTypeOfComponent() {
592         StorageOperationStatus result;
593         Component component = new Resource();
594         String id = "id";
595         component.setUniqueId(id);
596         String datatype = null;
597
598         DataTypeDefinition dataType1 = new DataTypeDefinition();
599         dataType1.setName("name1");
600         Map<String, DataTypeDataDefinition> dataTypeDataMap = new HashMap<>();
601         dataTypeDataMap.put("datatype1", dataType1);
602         List<DataTypeDefinition> dataTypeMap = dataTypeDataMap.values().stream().map(e -> { DataTypeDefinition dataType = new DataTypeDefinition(e);return dataType; }).collect(Collectors.toList());
603         component.setDataTypes(dataTypeMap);
604         GraphVertex graphVertex = getTopologyTemplateVertex();
605         result = testInstance.deleteDataTypeOfComponent(component, "datatype1");
606         assertEquals(datatype, result);
607     }
608
609     @Test
610     public void testAddComponentInstancePropertiesToComponent() {
611         // set up component object
612         Component component = new Resource();
613         component.setUniqueId(COMPONENT_ID);
614         List<ComponentInstanceProperty> instanceProps = new ArrayList<>();
615         ComponentInstanceProperty instanceProp = new ComponentInstanceProperty();
616         instanceProp.setName(PROPERTY1_NAME);
617         instanceProp.setType(PROPERTY1_TYPE);
618         instanceProps.add(instanceProp);
619         instanceProp = new ComponentInstanceProperty();
620         instanceProp.setName(PROPERTY2_NAME);
621         instanceProp.setType(PROPERTY2_TYPE);
622         instanceProps.add(instanceProp);
623         Map<String, List<ComponentInstanceProperty>> instancePropsMap =
624             Collections.singletonMap(COMPONENT_ID, instanceProps);
625         component.setComponentInstancesProperties(Collections.singletonMap(COMPONENT_ID, new ArrayList<>()));
626
627         when(nodeTemplateOperationMock.addComponentInstanceProperty(any(), any(), any()))
628             .thenReturn(StorageOperationStatus.OK);
629
630         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> result =
631             testInstance.addComponentInstancePropertiesToComponent(component, instancePropsMap);
632         assertTrue(result.isLeft());
633         verify(nodeTemplateOperationMock, times(2)).addComponentInstanceProperty(any(), any(), any());
634         List<ComponentInstanceProperty> resultProps = result.left().value().get(COMPONENT_ID);
635         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY1_NAME)));
636         assertTrue(resultProps.stream().anyMatch(e -> e.getName().equals(PROPERTY2_NAME)));
637     }
638
639     @Test
640     public void testAddComponentInstanceToTopologyTemplate() {
641         Component containerComponent = new Service();
642         Component originalComponent = new Service();
643         ComponentInstance componentInstance = new ComponentInstance();
644         ComponentInstance existingComponentInstance = new ComponentInstance();
645         User user = new User();
646
647         containerComponent.setComponentType(ComponentTypeEnum.SERVICE);
648
649         originalComponent.setComponentType(ComponentTypeEnum.SERVICE);
650         originalComponent.setIcon(ICON_NAME);
651
652         componentInstance.setOriginType(OriginTypeEnum.ServiceProxy);
653         componentInstance.setSourceModelName(SERVICE_MODEL_NAME);
654
655         List<ComponentInstance> existingInstances = new ArrayList<>();
656         existingComponentInstance.setNormalizedName(SERVICE_PROXY_INSTANCE0_NAME);
657         existingInstances.add(existingComponentInstance);
658         containerComponent.setComponentInstances(existingInstances);
659
660         when(nodeTemplateOperationMock
661             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user)))
662             .thenReturn(Either.left(new ImmutablePair<>(new TopologyTemplate(), COMPONENT_ID)));
663         TopologyTemplate topologyTemplate = new TopologyTemplate();
664         // preset COMPONENT_TYPE field for internal ModelConverter call
665         topologyTemplate.setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
666         when(topologyTemplateOperationMock.getToscaElement(containerComponent.getUniqueId()))
667             .thenReturn(Either.left(topologyTemplate));
668
669         Either<ImmutablePair<Component, String>, StorageOperationStatus> result =
670             testInstance.addComponentInstanceToTopologyTemplate(
671                 containerComponent, originalComponent, componentInstance, false, user);
672
673         assertTrue(result.isLeft());
674         assertEquals(componentInstance.getIcon(), ICON_NAME);
675         assertEquals(result.left().value().getRight(), COMPONENT_ID);
676         // the instance counter must be 1 because the service proxy instance with suffix 0 already exists.
677         verify(nodeTemplateOperationMock, times(1))
678             .addComponentInstanceToTopologyTemplate(any(), any(), eq("1"), eq(componentInstance), eq(false), eq(user));
679     }
680
681     private Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponentWithStatus(StorageOperationStatus status) {
682         PolicyDefinition policy = new PolicyDefinition();
683         String componentId = "componentId";
684         int counter = 0;
685         GraphVertex vertex;
686         if(status == StorageOperationStatus.OK){
687             vertex = getTopologyTemplateVertex();
688         } else {
689             vertex = getNodeTypeVertex();
690         }
691         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
692         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither);
693         when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status);
694         return testInstance.associatePolicyToComponent(componentId, policy, counter);
695     }
696
697     private Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponentWithStatus(StorageOperationStatus status) {
698         PolicyDefinition policy = new PolicyDefinition();
699         String componentId = "componentId";
700         GraphVertex vertex = getTopologyTemplateVertex();
701         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex));
702         when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status);
703         return testInstance.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.NONE);
704     }
705
706     private void removePolicyFromComponentWithStatus(StorageOperationStatus status) {
707         String componentId = "componentId";
708         String policyId = "policyId";
709         GraphVertex vertex = getTopologyTemplateVertex();
710         Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = Either.left(vertex);
711         when(janusGraphDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither);
712         when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status);
713         StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId);
714         assertSame(result, status);
715     }
716
717     private List<GraphVertex> getMockVertices(int numOfVertices) {
718         return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList());
719     }
720
721     private ToscaElement getResourceToscaElement(String id) {
722         ToscaElement toscaElement = new TopologyTemplate();
723         toscaElement.setMetadata(new HashMap<>());
724         toscaElement.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), "RESOURCE");
725         toscaElement.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), id);
726         return toscaElement;
727     }
728
729     private GraphVertex getTopologyTemplateVertex() {
730         GraphVertex graphVertex = new GraphVertex();
731         graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
732         return graphVertex;
733     }
734
735     private GraphVertex getNodeTypeVertex() {
736         GraphVertex graphVertex = new GraphVertex();
737         graphVertex.setLabel(VertexTypeEnum.NODE_TYPE);
738         return graphVertex;
739     }
740 }