Upgrade testing frameworks to latest not-vulnerable versions
[sdc.git] / openecomp-be / lib / openecomp-tosca-lib / src / test / java / org / openecomp / sdc / tosca / services / impl / ToscaAnalyzerServiceImplTest.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
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
17 package org.openecomp.sdc.tosca.services.impl;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.assertTrue;
23 import static org.mockito.Mockito.when;
24
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33
34 import org.apache.commons.io.IOUtils;
35 import org.hamcrest.core.StringContains;
36 import org.junit.Assert;
37 import org.junit.Before;
38 import org.junit.BeforeClass;
39 import org.junit.Rule;
40 import org.junit.Test;
41 import org.junit.rules.ExpectedException;
42 import org.junit.runner.RunWith;
43 import org.mockito.Mock;
44 import org.mockito.MockitoAnnotations;
45 import org.mockito.junit.MockitoJUnitRunner;
46 import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
47 import org.onap.sdc.tosca.datatypes.model.CapabilityType;
48 import org.onap.sdc.tosca.datatypes.model.Constraint;
49 import org.onap.sdc.tosca.datatypes.model.DataType;
50 import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType;
51 import org.onap.sdc.tosca.datatypes.model.Import;
52 import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
53 import org.onap.sdc.tosca.datatypes.model.InterfaceType;
54 import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
55 import org.onap.sdc.tosca.datatypes.model.NodeType;
56 import org.onap.sdc.tosca.datatypes.model.OperationDefinitionType;
57 import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
58 import org.onap.sdc.tosca.datatypes.model.PropertyDefinition;
59 import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
60 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
61 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
62 import org.onap.sdc.tosca.datatypes.model.Status;
63 import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping;
64 import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
65 import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
66 import org.openecomp.sdc.common.errors.CoreException;
67 import org.openecomp.sdc.common.errors.SdcRuntimeException;
68 import org.openecomp.sdc.tosca.TestUtil;
69 import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
70 import org.openecomp.sdc.tosca.datatypes.ToscaFlatData;
71 import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
72 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
73 import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
74 import org.openecomp.sdc.tosca.services.ToscaConstants;
75
76
77 @RunWith(MockitoJUnitRunner.class)
78 public class ToscaAnalyzerServiceImplTest {
79
80     private static final String CAPABILITY_TYPE_A = "capabilityTypeA";
81     private static final String CAPABILITY_TYPE_B = "capabilityTypeB";
82     private static final String TOSCA_CAPABILITIES_ROOT = "tosca.capabilities.Root";
83     private static final String CMAUI_IMAGE_EXTEND = "org.openecomp.resource.vfc.nodes.heat.cmaui_image_extend";
84     private static final String STANDARD_INTERFACE_KEY = "Standard";
85     private static final String TOSCA_LIFECYCLE_STANDARD = "tosca.interfaces.node.lifecycle.Standard";
86     private static final String CMAUI_INTERFACE_TEST =
87             "org.openecomp.resource.vfc.nodes.heat.cmaui_image_interfaceTest";
88     private static final String NODE_TYPE_NO_INTERFACE = "org.openecomp.resource.vfc.nodes.nodeBNoInterface";
89
90     /*
91     Dictionary:
92     SrvTmp: ServiceTemplate
93     NdTmp: NodeTemplate
94     NdTy: NodeType
95     */
96
97     private static ToscaAnalyzerService toscaAnalyzerService;
98     private static ToscaServiceModel toscaServiceModel;
99     @Rule
100     public ExpectedException thrown = ExpectedException.none();
101
102     @Mock
103     private NodeTemplate nodeTemplateMock;
104     @Mock
105     private ParameterDefinition parameterDefinitionMock;
106     @Mock
107     private PropertyDefinition propertyDefinitionMock;
108     @Mock
109     private InterfaceDefinitionType interfaceDefinitionMock;
110     @Mock
111     private ToscaServiceModel toscaServiceModelMock;
112
113     @BeforeClass
114     public static void onlyOnceSetUp() throws IOException {
115         toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
116         toscaServiceModel = TestUtil.loadToscaServiceModel("/mock/analyzerService/toscasubstitution/",
117                 "/mock/globalServiceTemplates/", null);
118     }
119
120     @Before
121     public void init() {
122         MockitoAnnotations.openMocks(this);
123     }
124
125     @Test
126     public void testGetFlatEntityNotFound() throws Exception {
127         thrown.expect(CoreException.class);
128         thrown.expectMessage(
129                 "Entity Type 'org.openecomp.resource.vfc.notFound' or one of its derivedFrom type "
130                         + "hierarchy, is not defined in tosca service model");
131         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
132         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
133                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
134
135             ServiceTemplate serviceTemplateFromYaml =
136                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
137
138             toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.notFound",
139                     serviceTemplateFromYaml, toscaServiceModel);
140         }
141     }
142
143     @Test
144     public void testGetFlatEntityFileNotFound() throws Exception {
145         thrown.expect(CoreException.class);
146         thrown.expectMessage("Tosca file 'missingFile.yaml' was not found in tosca service model");
147         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
148         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
149                 "/mock/analyzerService/ServiceTemplateFileNotFoundTest.yaml")) {
150
151             ServiceTemplate serviceTemplateFromYaml =
152                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
153
154             toscaAnalyzerService
155                     .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.nodes.heat.cmaui_image",
156                             serviceTemplateFromYaml, toscaServiceModel);
157         }
158     }
159
160     @Test
161     public void testGetFlatEntityNodeType() throws Exception {
162         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
163         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
164                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
165
166             ServiceTemplate serviceTemplateFromYaml =
167                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
168
169             ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE,
170                     "org.openecomp.resource.vfc.nodes.heat" + ".cmaui_image", serviceTemplateFromYaml,
171                     toscaServiceModel);
172
173             Assert.assertNotNull(flatData);
174             checkNodeTypeFlatEntity(flatData);
175             checkNodeTypeInheritanceHierarchy(flatData);
176         }
177     }
178
179     private void checkNodeTypeInheritanceHierarchy(ToscaFlatData flatData) {
180         List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
181         Assert.assertNotNull(inheritanceHierarchyType);
182         Assert.assertEquals(4, inheritanceHierarchyType.size());
183         Assert.assertTrue(inheritanceHierarchyType.contains("org.openecomp.resource.vfc.nodes.heat.cmaui_image"));
184         Assert.assertTrue(inheritanceHierarchyType.contains("org.openecomp.resource.vfc.nodes.heat.nova.Server"));
185         Assert.assertTrue(inheritanceHierarchyType.contains("tosca.nodes.Compute"));
186         Assert.assertTrue(inheritanceHierarchyType.contains("tosca.nodes.Root"));
187     }
188
189     private void checkNodeTypeFlatEntity(ToscaFlatData flatData) {
190         Assert.assertNotNull(flatData.getFlatEntity());
191         NodeType flatEntity = (NodeType) flatData.getFlatEntity();
192         Assert.assertEquals("org.openecomp.resource.vfc.nodes.heat.nova.Server", flatEntity.getDerived_from());
193         Assert.assertEquals(20, flatEntity.getProperties().size());
194         Assert.assertEquals("overridden default value", flatEntity.getProperties().get("admin_pass").get_default());
195         Assert.assertEquals("REBUILD", flatEntity.getProperties().get("image_update_policy").get_default());
196         Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
197     }
198
199     @Test
200     public void testGetFlatEntityNodeTypeInterface() throws Exception {
201         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
202         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
203                 "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml")) {
204
205             ServiceTemplate serviceTemplateFromYaml =
206                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
207
208             ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, CMAUI_IMAGE_EXTEND,
209                     serviceTemplateFromYaml, toscaServiceModel);
210
211             Assert.assertNotNull(flatData);
212             Assert.assertNotNull(flatData.getFlatEntity());
213             NodeType flatEntity = (NodeType) flatData.getFlatEntity();
214             Assert.assertNotNull(flatEntity.getInterfaces());
215             Object standardInterfaceObj = flatEntity.getInterfaces().get(STANDARD_INTERFACE_KEY);
216             Assert.assertNotNull(standardInterfaceObj);
217             InterfaceDefinitionType standardInterface = new InterfaceDefinitionType(standardInterfaceObj);
218             Assert.assertEquals(2, standardInterface.getInputs().size());
219             Assert.assertEquals(3, standardInterface.getOperations().size());
220             OperationDefinitionType createOperation = toscaExtensionYamlUtil.yamlToObject(
221                     toscaExtensionYamlUtil.objectToYaml(standardInterface.getOperations().get("create")),
222                     OperationDefinitionType.class);
223             Assert.assertEquals(2, createOperation.getInputs().size());
224
225             List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
226             Assert.assertNotNull(inheritanceHierarchyType);
227             Assert.assertEquals(5, inheritanceHierarchyType.size());
228         }
229     }
230
231     @Test
232     public void testGetFlatNodeTypeNoInterfaces() throws Exception {
233         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
234         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
235                 "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml")) {
236
237             ServiceTemplate serviceTemplateFromYaml =
238                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
239
240             ToscaFlatData flatData = toscaAnalyzerService
241                                              .getFlatEntity(ToscaElementTypes.NODE_TYPE, NODE_TYPE_NO_INTERFACE,
242                                                      serviceTemplateFromYaml, toscaServiceModel);
243
244             Assert.assertNotNull(flatData);
245             Assert.assertNotNull(flatData.getFlatEntity());
246             NodeType flatEntity = (NodeType) flatData.getFlatEntity();
247             Assert.assertNull(flatEntity.getInterfaces());
248             List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
249             Assert.assertNotNull(inheritanceHierarchyType);
250             Assert.assertEquals(2, inheritanceHierarchyType.size());
251         }
252     }
253
254
255     @Test
256     public void testGetFlatEntityDataType() throws Exception {
257         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
258         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
259                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
260
261             ServiceTemplate serviceTemplateFromYaml =
262                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
263
264             ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.DATA_TYPE,
265                     "org.openecomp.datatypes.heat.network.MyNewAddressPair", serviceTemplateFromYaml,
266                     toscaServiceModel);
267
268             Assert.assertNotNull(flatData);
269             Assert.assertNotNull(flatData.getFlatEntity());
270             DataType flatEntity = (DataType) flatData.getFlatEntity();
271             Assert.assertEquals("org.openecomp.datatypes.heat.network.MyAddressPair", flatEntity.getDerived_from());
272             Assert.assertEquals(3, flatEntity.getProperties().size());
273             Assert.assertEquals("overridden default value",
274                     flatEntity.getProperties().get("mac_address").get_default());
275             Assert.assertEquals(true, flatEntity.getProperties().get("mac_address").getRequired());
276             Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
277
278             List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
279             Assert.assertNotNull(inheritanceHierarchyType);
280             Assert.assertEquals(4, inheritanceHierarchyType.size());
281         }
282     }
283
284     @Test
285     public void testGetFlatEntityDataTypeDerivedFromPrimitive() throws Exception {
286         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
287         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
288                 "/mock/analyzerService/ServiceTemplateDatatypeFlatTest.yaml")) {
289
290             ServiceTemplate serviceTemplateFromYaml =
291                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
292
293             ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.DATA_TYPE,
294                     "org.openecomp.datatypes.heat.network.MyNewString", serviceTemplateFromYaml, toscaServiceModel);
295
296             Assert.assertNotNull(flatData);
297             Assert.assertNotNull(flatData.getFlatEntity());
298             DataType flatEntity = (DataType) flatData.getFlatEntity();
299             Assert.assertEquals("org.openecomp.datatypes.heat.network.MyString", flatEntity.getDerived_from());
300             Assert.assertEquals(2, flatEntity.getConstraints().size());
301             Assert.assertNotNull(flatEntity.getConstraints().get(0).getValid_values());
302             Assert.assertNotNull(flatEntity.getConstraints().get(1).getMax_length());
303
304             List<String> inheritanceHierarchyType = flatData.getInheritanceHierarchyType();
305             Assert.assertNotNull(inheritanceHierarchyType);
306             Assert.assertEquals(2, inheritanceHierarchyType.size());
307         }
308     }
309
310     @Test
311     public void testCalculateExposedRequirementsNull() {
312         assertTrue(toscaAnalyzerService.calculateExposedRequirements(null, null).isEmpty());
313     }
314
315     @Test
316     public void testCalculateExposedRequirements() {
317         RequirementDefinition rd = new RequirementDefinition();
318         rd.setCapability("tosca.capabilities.Node");
319         rd.setNode("tosca.nodes.Root");
320         rd.setRelationship("tosca.relationships.DependsOn");
321         Object[] occurences = new Object[] {0, "UNBOUNDED"};
322         rd.setOccurrences(occurences);
323
324         rd.setCapability("tosca.capabilities.network.Bindable");
325         rd.setNode(null);
326         rd.setRelationship("tosca.relationships.network.BindsTo");
327         Object[] occurences1 = new Object[] {1, 1};
328         RequirementDefinition rd1 = new RequirementDefinition();
329         rd1.setOccurrences(occurences1);
330
331         Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
332         nodeTypeRequirementDefinition.put("binding", rd1);
333         nodeTypeRequirementDefinition.put("dependency", rd);
334
335         RequirementAssignment ra = new RequirementAssignment();
336         ra.setCapability("tosca.capabilities.network.Bindable");
337         ra.setNode("pd_server");
338         ra.setRelationship("tosca.relationships.network.BindsTo");
339         Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
340         nodeTemplateRequirementsAssignment.put("binding", ra);
341
342         List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
343         nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
344
345         List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
346                 .calculateExposedRequirements(
347                         nodeTypeRequirementsDefinition,
348                         nodeTemplateRequirementsAssignment);
349         Assert.assertEquals(1, exposedRequirements.size());
350     }
351
352     @Test
353     public void testCalExpReqWithNullNodeInReqAssignment() {
354         RequirementDefinition rd = new RequirementDefinition();
355         rd.setCapability("tosca.capabilities.Node");
356         rd.setNode("tosca.nodes.Root");
357         rd.setRelationship("tosca.relationships.DependsOn");
358         Object[] occurences = new Object[] {0, "UNBOUNDED"};
359         rd.setOccurrences(occurences);
360
361         rd.setCapability("tosca.capabilities.network.Bindable");
362         rd.setNode(null);
363         rd.setRelationship("tosca.relationships.network.BindsTo");
364         Object[] occurences1 = new Object[] {1, 1};
365         RequirementDefinition rd1 = new RequirementDefinition();
366         rd1.setOccurrences(occurences1);
367
368         Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
369         nodeTypeRequirementDefinition.put("binding", rd1);
370         nodeTypeRequirementDefinition.put("dependency", rd);
371
372         RequirementAssignment ra = new RequirementAssignment();
373         ra.setCapability("tosca.capabilities.network.Bindable");
374         ra.setNode(null);
375         ra.setRelationship("tosca.relationships.network.BindsTo");
376         Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
377         nodeTemplateRequirementsAssignment.put("binding", ra);
378
379         List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
380         nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
381
382         List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
383                 .calculateExposedRequirements(
384                         nodeTypeRequirementsDefinition,
385                         nodeTemplateRequirementsAssignment);
386         Assert.assertEquals(1, exposedRequirements.size());
387     }
388
389     @Test
390     public void testCalculateExposedCapabilities() {
391         Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
392         CapabilityDefinition cd = new CapabilityDefinition();
393         cd.setType("tosca.capabilities.Scalable");
394         nodeTypeCapabilitiesDefinition.put("tosca.capabilities.network.Bindable_pd_server", cd);
395         RequirementAssignment ra = new RequirementAssignment();
396         ra.setCapability("tosca.capabilities.network.Bindable");
397         ra.setNode("pd_server");
398         ra.setRelationship("tosca.relationships.network.BindsTo");
399         Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
400         nodeTemplateRequirementsAssignment.put("binding", ra);
401         Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
402         fullFilledRequirementsDefinition.put("pd_server", nodeTemplateRequirementsAssignment);
403         Map<String, CapabilityDefinition> exposedCapabilities = toscaAnalyzerService.calculateExposedCapabilities(
404                 nodeTypeCapabilitiesDefinition, fullFilledRequirementsDefinition);
405         Assert.assertEquals(1, exposedCapabilities.size());
406     }
407
408     @Test
409     public void testIsRequirementExistsWithInvalidReqId() throws Exception {
410         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
411         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
412                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
413
414             ServiceTemplate serviceTemplateFromYaml =
415                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
416
417             TestUtil.createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil);
418
419
420             RequirementAssignment ra = new RequirementAssignment();
421             ra.setCapability("tosca.capabilities.network.Bindable");
422             ra.setNode("server_cmaui");
423             ra.setRelationship("tosca.relationships.network.BindsTo");
424
425             NodeTemplate port0 = serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
426             //Test With Empty requirementId
427             Assert.assertFalse(toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "", ra));
428
429             //Test With valid requirementId
430             Assert.assertTrue(toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "binding", ra));
431
432             //Test With invalid requirement assignment
433             RequirementAssignment ra1 = new RequirementAssignment();
434             ra1.setCapability("tosca.capabilities.network.Bindable1");
435             ra1.setNode("server_cmaui1");
436             ra1.setRelationship("tosca.relationships.network.BindsTo1");
437             Assert.assertFalse(toscaAnalyzerService.isRequirementExistInNodeTemplate(port0, "binding", ra1));
438         }
439     }
440
441     @Test
442     public void testGetRequirements() throws Exception {
443         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
444         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
445                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
446
447             ServiceTemplate serviceTemplateFromYaml =
448                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
449
450             NodeTemplate port0 = serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
451             List<RequirementAssignment> reqList =
452                     toscaAnalyzerService.getRequirements(port0, ToscaConstants.BINDING_REQUIREMENT_ID);
453             assertEquals(1, reqList.size());
454
455             reqList.clear();
456             NodeTemplate port1 =
457                     serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1");
458             reqList = toscaAnalyzerService.getRequirements(port1, ToscaConstants.LINK_REQUIREMENT_ID);
459             assertEquals(2, reqList.size());
460
461             reqList.clear();
462             reqList = toscaAnalyzerService.getRequirements(port0, ToscaConstants.LINK_REQUIREMENT_ID);
463             assertEquals(0, reqList.size());
464         }
465     }
466
467     @Test
468     public void testGetNodeTemplateById() {
469         ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
470         Optional<NodeTemplate> nodeTemplate =
471                 toscaAnalyzerService.getNodeTemplateById(emptyServiceTemplate, "test_net222");
472         assertFalse(nodeTemplate.isPresent());
473
474         ServiceTemplate mainServiceTemplate =
475                 toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
476         nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
477         assertTrue(nodeTemplate.isPresent());
478
479         nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net222");
480         assertFalse(nodeTemplate.isPresent());
481     }
482
483     @Test
484     public void testGetSubstituteServiceTemplateName() {
485         thrown.expect(CoreException.class);
486         thrown.expectMessage(
487                 "Invalid Substitute Node Template invalid2, mandatory map property service_template_filter "
488                         + "with mandatory key substitute_service_template must be defined.");
489
490         Optional<String> substituteServiceTemplateName;
491
492         ServiceTemplate mainServiceTemplate =
493                 toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
494         Optional<NodeTemplate> notSubstitutableNodeTemplate =
495                 toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
496         assertTrue(notSubstitutableNodeTemplate.isPresent());
497
498         substituteServiceTemplateName = toscaAnalyzerService.getSubstituteServiceTemplateName("test_net",
499                 notSubstitutableNodeTemplate.get());
500         assertFalse(substituteServiceTemplateName.isPresent());
501
502         Optional<NodeTemplate> substitutableNodeTemplate =
503                 toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_nested");
504         assertTrue(substitutableNodeTemplate.isPresent());
505
506         substituteServiceTemplateName = toscaAnalyzerService.getSubstituteServiceTemplateName("test_nested",
507                 substitutableNodeTemplate.get());
508         assertTrue(substituteServiceTemplateName.isPresent());
509         assertEquals("nestedServiceTemplate.yaml", substituteServiceTemplateName.get());
510
511         NodeTemplate invalidSubstitutableNodeTemplate1 = new NodeTemplate();
512         substituteServiceTemplateName =
513                 toscaAnalyzerService.getSubstituteServiceTemplateName("invalid1", invalidSubstitutableNodeTemplate1);
514         assertFalse(substituteServiceTemplateName.isPresent());
515
516         substitutableNodeTemplate.ifPresent(nodeTemplate -> {
517             Object serviceTemplateFilter =
518                     nodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
519             ((Map) serviceTemplateFilter).clear();
520             toscaAnalyzerService.getSubstituteServiceTemplateName("invalid2", nodeTemplate);
521
522         });
523     }
524
525
526     @Test
527     public void testGetSubstitutableNodeTemplates() throws Exception {
528         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
529         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
530                 "/mock/analyzerService/ServiceTemplateSubstituteTest.yaml")) {
531             ServiceTemplate serviceTemplateFromYaml =
532                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
533
534             Map<String, NodeTemplate> substitutableNodeTemplates =
535                     toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
536             assertEquals(2, substitutableNodeTemplates.size());
537             assertNotNull(substitutableNodeTemplates.get("test_nested1"));
538             assertNotNull(substitutableNodeTemplates.get("test_nested2"));
539
540             ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
541             emptyServiceTemplate.setTopology_template(new TopologyTemplate());
542             substitutableNodeTemplates = toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate);
543             assertEquals(0, substitutableNodeTemplates.size());
544         }
545
546         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
547                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
548             ServiceTemplate serviceTemplateFromYaml =
549                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
550             Map<String, NodeTemplate> substitutableNodeTemplates =
551                     toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
552             assertEquals(0, substitutableNodeTemplates.size());
553         }
554     }
555
556     @Test
557     public void testGetSubstitutionMappedNodeTemplateByExposedReq() throws Exception {
558         thrown.expect(CoreException.class);
559         thrown.expectMessage(
560                 "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
561         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
562         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
563                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
564             ServiceTemplate nestedServiceTemplateFromYaml =
565                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
566
567             Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate =
568                     toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
569                             "NestedServiceTemplateSubstituteTest.yaml",
570                             nestedServiceTemplateFromYaml,
571                             "local_storage_server_cmaui");
572
573             assertTrue(mappedNodeTemplate.isPresent());
574             mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
575                 assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
576                 assertNotNull(stringNodeTemplateEntry.getValue());
577             });
578
579             mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
580                     "NestedServiceTemplateSubstituteTest.yaml", nestedServiceTemplateFromYaml,
581                     "link_cmaui_port_invalid");
582             assertTrue(mappedNodeTemplate.isPresent());
583             mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
584                 assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
585                 assertNotNull(stringNodeTemplateEntry.getValue());
586             });
587
588             ServiceTemplate mainServiceTemplate =
589                     toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
590             mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
591                     toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
592                     "local_storage_server_cmaui");
593             assertFalse(mappedNodeTemplate.isPresent());
594         }
595     }
596
597     @Test
598     public void invalidSubstitutableMapping() {
599         thrown.expect(CoreException.class);
600         thrown.expectMessage(
601                 "Invalid Substitution Service Template invalidMappingServiceTemplate.yaml, "
602                         + "missing mandatory file 'Node type' in substitution mapping.");
603         ServiceTemplate invalidMappingServiceTemplate = new ServiceTemplate();
604         invalidMappingServiceTemplate.setTopology_template(new TopologyTemplate());
605         invalidMappingServiceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
606         toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq("invalidMappingServiceTemplate.yaml",
607                 invalidMappingServiceTemplate, "local_storage_server_cmaui");
608     }
609
610     @Test
611     public void substitutableMappingWithNoReqMap() {
612         ServiceTemplate emptyReqMapping = new ServiceTemplate();
613         emptyReqMapping.setTopology_template(new TopologyTemplate());
614         emptyReqMapping.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
615         emptyReqMapping.getTopology_template().getSubstitution_mappings().setNode_type("temp");
616         ServiceTemplate mainServiceTemplate =
617                 toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
618         Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate =
619                 toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
620                         toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
621                         "local_storage_server_cmaui");
622         assertFalse(mappedNodeTemplate.isPresent());
623     }
624
625     @Test
626     public void testGetSubstitutionMappedNodeTemplateByExposedReqInvalid() throws Exception {
627         thrown.expect(CoreException.class);
628         thrown.expectMessage(
629                 "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
630         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
631         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
632                 "/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
633             ServiceTemplate nestedServiceTemplateFromYaml =
634                     toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
635
636             toscaAnalyzerService
637                     .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
638                             nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
639         }
640     }
641
642     @Test
643     public void testIsDesiredRequirementAssignmentMatch() {
644
645         RequirementAssignment requirementAssignment = new RequirementAssignment();
646         String capability = "Test.Capability";
647         String node = "Test.node";
648         String relationship = "Test.relationship";
649         requirementAssignment.setCapability(capability);
650         requirementAssignment.setNode(node);
651         requirementAssignment.setRelationship(relationship);
652
653         assertTrue(toscaAnalyzerService
654                 .isDesiredRequirementAssignment(requirementAssignment, capability, node, relationship));
655         assertTrue(
656                 toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, node, relationship));
657         assertTrue(toscaAnalyzerService
658                 .isDesiredRequirementAssignment(requirementAssignment, capability, null, relationship));
659         assertTrue(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, node, null));
660         assertTrue(
661                 toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, null, relationship));
662         assertTrue(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, null, null));
663         assertTrue(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, node, null));
664
665     }
666
667     @Test
668     public void testIsDesiredRequirementAssignmentNoMatch() {
669
670         RequirementAssignment requirementAssignment = new RequirementAssignment();
671         String capability = "Test.Capability";
672         String node = "Test.node";
673         String relationship = "Test.relationship";
674         requirementAssignment.setCapability(capability);
675         requirementAssignment.setNode(node);
676         requirementAssignment.setRelationship(relationship);
677
678         assertFalse(
679                 toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", node, relationship));
680         assertFalse(
681                 toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", "no", relationship));
682         assertFalse(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", "no", "no"));
683         assertFalse(toscaAnalyzerService
684                 .isDesiredRequirementAssignment(requirementAssignment, capability, "no", relationship));
685         assertFalse(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, node, "no"));
686         assertFalse(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, capability, "no", "no"));
687         assertFalse(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, "no", null, null));
688         assertFalse(toscaAnalyzerService.isDesiredRequirementAssignment(requirementAssignment, null, null, null));
689
690
691     }
692
693     @Test
694     public void shouldReturnFalseIfNdTmpIsNull() {
695         NodeTemplate nodeTemplate = null;
696         assertFalse(toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NATIVE_NETWORK, new ServiceTemplate(),
697                 toscaServiceModelMock));
698     }
699
700     @Test
701     public void shouldReturnTrueIfNdTmpTypeIsOfRequestedType() {
702         NodeTemplate nodeTemplate = new NodeTemplate();
703         String nodeTypeToSearch = ToscaNodeType.NATIVE_BLOCK_STORAGE;
704         nodeTemplate.setType(nodeTypeToSearch);
705         assertTrue(toscaAnalyzerService
706                 .isTypeOf(nodeTemplate, nodeTypeToSearch, new ServiceTemplate(), toscaServiceModelMock));
707     }
708
709     @Test
710     public void shouldReturnTrueIfDataTypeIsOfRequestedType() {
711         PropertyDefinition propertyDefinition = new PropertyDefinition();
712         String propertyTypeToSearch = "tosca.datatypes.TimeInterval";
713         propertyDefinition.setType(propertyTypeToSearch);
714         assertTrue(toscaAnalyzerService.isTypeOf(propertyDefinition, propertyTypeToSearch, new ServiceTemplate(),
715                 toscaServiceModelMock));
716     }
717
718     @Test
719     public void shouldReturnTrueIfInterfaceTypeIsOfRequestedType() {
720         InterfaceDefinitionType interfaceDefinition = new InterfaceDefinitionType();
721         String interfaceTypeToSearch = "test.interface.A";
722         interfaceDefinition.setType(interfaceTypeToSearch);
723         assertTrue(toscaAnalyzerService.isTypeOf(interfaceDefinition, interfaceTypeToSearch, new ServiceTemplate(),
724                 toscaServiceModelMock));
725     }
726
727     @Test
728     public void interfaceInheritanceNoOperIsTypeTrue() throws IOException {
729         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
730         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
731                 "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml")) {
732             interfaceIsTypeTest(toscaExtensionYamlUtil, CMAUI_IMAGE_EXTEND, yamlFile);
733         }
734     }
735
736     private void interfaceIsTypeTest(ToscaExtensionYamlUtil toscaExtensionYamlUtil, String nodeTypeKey,
737                                      InputStream yamlFile) {
738         ServiceTemplate serviceTemplateFromYaml = toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
739
740         ToscaFlatData flatData = toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeKey,
741                 serviceTemplateFromYaml, toscaServiceModel);
742
743         Assert.assertNotNull(flatData);
744         Object standardInterfaceDefinition =
745                 ((NodeType) flatData.getFlatEntity()).getInterfaces().get(STANDARD_INTERFACE_KEY);
746         InterfaceDefinitionType standardInterfaceDefinitionType =
747                 new InterfaceDefinitionType(standardInterfaceDefinition);
748         assertTrue(toscaAnalyzerService
749                 .isTypeOf(standardInterfaceDefinitionType, TOSCA_LIFECYCLE_STANDARD, serviceTemplateFromYaml,
750                         toscaServiceModel));
751     }
752
753     @Test
754     public void interfaceInheritanceWithOperIsTypeTrue() throws IOException {
755         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
756         try (InputStream yamlFile = toscaExtensionYamlUtil.loadYamlFileIs(
757                 "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml")) {
758             interfaceIsTypeTest(toscaExtensionYamlUtil, CMAUI_INTERFACE_TEST, yamlFile);
759         }
760     }
761
762
763     @Test
764     public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNdTyDerivedFromRequestedType() {
765         String typeToMatch = ToscaNodeType.CINDER_VOLUME;
766         when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
767         Map<String, NodeType> stNodeTypes = new HashMap<>();
768         addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
769         NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
770         addNodeType(stNodeTypes, typeToMatch, nodeType);
771         ServiceTemplate serviceTemplate = new ServiceTemplate();
772         serviceTemplate.setNode_types(stNodeTypes);
773         assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, serviceTemplate,
774                 toscaServiceModelMock));
775
776     }
777
778     @Test
779     public void dataTypeParameterExistInHierarchy() {
780         String testedDataTypeKey = "test.dataType.B";
781         when(parameterDefinitionMock.getType()).thenReturn(testedDataTypeKey);
782         dataTypeExistInHierarchy(testedDataTypeKey, parameterDefinitionMock);
783
784     }
785
786     @Test
787     public void dataTypePropertyExistInHierarchy() {
788         String testedDataTypeKey = "test.dataType.B";
789         when(propertyDefinitionMock.getType()).thenReturn(testedDataTypeKey);
790         dataTypeExistInHierarchy(testedDataTypeKey, propertyDefinitionMock);
791     }
792
793     private void dataTypeExistInHierarchy(String testedDataTypeKey, DefinitionOfDataType testedDefinitionDataType) {
794         String typeToMatch = "test.dataType.A";
795         Map<String, DataType> stDataTypes = new HashMap<>();
796         addDataType(stDataTypes, "tosca.datatypes.network.NetworkInfo", new DataType());
797         DataType testedDataType = createDataType(typeToMatch);
798         addDataType(stDataTypes, testedDataTypeKey, testedDataType);
799         ServiceTemplate serviceTemplate = new ServiceTemplate();
800         serviceTemplate.setData_types(stDataTypes);
801         assertTrue(toscaAnalyzerService
802                 .isTypeOf(testedDefinitionDataType, typeToMatch, serviceTemplate, toscaServiceModelMock));
803     }
804
805     @Test
806     public void interfaceTypeExistInHierarchy() {
807         String typeToMatch = "test.interfaceType.A";
808         String testedInterfaceTypeKey = "test.interfaceType.B";
809         when(interfaceDefinitionMock.getType()).thenReturn(testedInterfaceTypeKey);
810         Map<String, Object> stInterfaceTypes = new HashMap<>();
811         stInterfaceTypes.put("tosca.interfaces.network.NetworkInfo", new InterfaceType());
812         InterfaceType testedInterfaceType = createInterfaceType(typeToMatch);
813         stInterfaceTypes.put(testedInterfaceTypeKey, testedInterfaceType);
814         ServiceTemplate serviceTemplate = new ServiceTemplate();
815         serviceTemplate.setInterface_types(stInterfaceTypes);
816         assertTrue(toscaAnalyzerService.isTypeOf(interfaceDefinitionMock, "test.interfaceType.A", serviceTemplate,
817                 toscaServiceModelMock));
818     }
819
820     @Test
821     public void shouldThrowCoreExceptionForInvalidNodeType() {
822         thrown.expect(CoreException.class);
823         thrown.expectMessage("Entity Type 'AAA' or one of its derivedFrom type hierarchy, is not defined in "
824                 + "tosca service model");
825         when(nodeTemplateMock.getType()).thenReturn("AAA");
826         Map<String, NodeType> stNodeTypes = new HashMap<>();
827         addNodeType(stNodeTypes, "notImportant", new NodeType());
828         ServiceTemplate serviceTemplate = new ServiceTemplate();
829         serviceTemplate.setNode_types(stNodeTypes);
830         toscaAnalyzerService
831                 .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_COMPUTE, serviceTemplate, toscaServiceModelMock);
832     }
833
834     @Test
835     public void shouldThrowCoreExceptionForInvalidNodeType2Level() {
836         thrown.expect(CoreException.class);
837         thrown.expectMessage(
838                 "Entity Type 'A' or one of its derivedFrom type hierarchy, is not defined in tosca " + "service model");
839         String typeToMatch = "A";
840         when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
841         Map<String, NodeType> stNodeTypes = new HashMap<>();
842         addNodeType(stNodeTypes, "notImportant", new NodeType());
843         addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
844         addNodeType(stNodeTypes, "ADerivedFromB'", createNodeType("BDerivedFromC"));
845         ServiceTemplate serviceTemplate = new ServiceTemplate();
846         serviceTemplate.setNode_types(stNodeTypes);
847         assertTrue(toscaAnalyzerService
848                 .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
849     }
850
851     @Test
852     public void
853     shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNotDerivedFromRequestedTypeBut2ndLevelDerivedFromMatch() {
854         String typeToMatch = "A";
855         when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
856         Map<String, NodeType> stNodeTypes = new HashMap<>();
857         addNodeType(stNodeTypes, "notImportant", new NodeType());
858         addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
859         addNodeType(stNodeTypes, "ADerivedFromB", createNodeType("BDerivedFromC"));
860         ServiceTemplate serviceTemplate = new ServiceTemplate();
861         serviceTemplate.setNode_types(stNodeTypes);
862         assertTrue(toscaAnalyzerService
863                 .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
864     }
865
866     private NodeType createNodeType(String derivedFrom) {
867         NodeType nodeType = new NodeType();
868         nodeType.setDerived_from(derivedFrom);
869         return nodeType;
870     }
871
872     private DataType createDataType(String derivedFrom) {
873         DataType dataType = new DataType();
874         dataType.setDerived_from(derivedFrom);
875         return dataType;
876     }
877
878     private InterfaceType createInterfaceType(String derivedFrom) {
879         InterfaceType interfaceType = new InterfaceType();
880         interfaceType.setDerived_from(derivedFrom);
881         return interfaceType;
882     }
883
884     private void addNodeType(Map<String, NodeType> stNodeTypes, String key, NodeType nodeType) {
885         stNodeTypes.put(key, nodeType);
886     }
887
888     private void addDataType(Map<String, DataType> stDataTypes, String key, DataType dataType) {
889         stDataTypes.put(key, dataType);
890     }
891
892     @Test
893     public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn1stLevelImports() {
894         String typeToMatch = ToscaNodeType.CINDER_VOLUME;
895         when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
896         List<Map<String, Import>> imports = new ArrayList<>();
897         Map<String, Import> importMap = new HashMap<>();
898         Import anImport = new Import();
899         anImport.setFile("mainImport");
900         importMap.put("bla bla", anImport);
901         imports.add(importMap);
902         ServiceTemplate mainSt = new ServiceTemplate();
903         mainSt.setImports(imports);
904
905         //create searchable service template
906         Map<String, NodeType> stNodeTypes = new HashMap<>();
907         addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
908         NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
909         addNodeType(stNodeTypes, typeToMatch, nodeType);
910         ServiceTemplate serviceTemplate = new ServiceTemplate();
911         serviceTemplate.setNode_types(stNodeTypes);
912
913         // add service templates to tosca service model
914         Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
915         serviceTemplates.put("testMainServiceTemplate", mainSt);
916         serviceTemplates.put("mainImport", serviceTemplate);
917         when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
918
919         assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainSt,
920                 toscaServiceModelMock));
921     }
922
923     @Test
924     public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn2ndLevelImports() {
925         String typeToMatch = ToscaNodeType.CINDER_VOLUME;
926         when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
927         List<Map<String, Import>> imports = new ArrayList<>();
928         Map<String, Import> importMap = new HashMap<>();
929         Import anImport = new Import();
930         anImport.setFile("refToMainImport");
931         importMap.put("bla bla", anImport);
932         imports.add(importMap);
933         ServiceTemplate mainSt = new ServiceTemplate();
934         mainSt.setImports(imports);
935
936         //create searchable service template
937         Map<String, NodeType> stNodeTypes = new HashMap<>();
938         addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
939         NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
940         addNodeType(stNodeTypes, typeToMatch, nodeType);
941         ServiceTemplate serviceTemplate = new ServiceTemplate();
942         serviceTemplate.setNode_types(stNodeTypes);
943
944         // create 1st level service template with import only
945         List<Map<String, Import>> firstLevelImports = new ArrayList<>();
946         Map<String, Import> firstLevelImportsMap = new HashMap<>();
947         Import firstLevelImport = new Import();
948         firstLevelImport.setFile("mainImport");
949         firstLevelImportsMap.put("bla bla 2", firstLevelImport);
950         firstLevelImports.add(firstLevelImportsMap);
951         ServiceTemplate firstLevelSt = new ServiceTemplate();
952         firstLevelSt.setImports(firstLevelImports);
953
954         // add service templates to tosca service model
955         Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
956         serviceTemplates.put("testMainServiceTemplate", mainSt);
957         serviceTemplates.put("refToMainImport", firstLevelSt);
958         serviceTemplates.put("mainImport", serviceTemplate);
959         when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
960
961         assertTrue(toscaAnalyzerService.isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainSt,
962                 toscaServiceModelMock));
963     }
964
965     // not found at all should throw core exception
966
967
968     @Test
969     public void capabilityDefinitionIsTypeOfDirectTypeFound() {
970         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
971         capabilityDefinition.setType(CAPABILITY_TYPE_A);
972         assertTrue(toscaAnalyzerService.isTypeOf(capabilityDefinition, CAPABILITY_TYPE_A, new ServiceTemplate(),
973                 toscaServiceModelMock));
974     }
975
976     @Test
977     public void capabilityDefinitionIsTypeOfReturnNo() {
978         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
979         capabilityDefinition.setType(CAPABILITY_TYPE_A);
980         ServiceTemplate serviceTemplate = new ServiceTemplate();
981         serviceTemplate.setCapability_types(new HashMap<>());
982         CapabilityType capabilityType = new CapabilityType();
983         capabilityType.setDerived_from(TOSCA_CAPABILITIES_ROOT);
984         serviceTemplate.getCapability_types().put(CAPABILITY_TYPE_A, capabilityType);
985         assertFalse(toscaAnalyzerService
986                 .isTypeOf(capabilityDefinition, CAPABILITY_TYPE_B, serviceTemplate, toscaServiceModelMock));
987     }
988
989     @Test
990     public void capabilityDefinitionIsTypeOfInheritanceTypeFound() {
991         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
992         capabilityDefinition.setType(CAPABILITY_TYPE_A);
993         ServiceTemplate serviceTemplate = new ServiceTemplate();
994         serviceTemplate.setCapability_types(new HashMap<>());
995         CapabilityType capabilityType = new CapabilityType();
996         capabilityType.setDerived_from(CAPABILITY_TYPE_B);
997         serviceTemplate.getCapability_types().put(CAPABILITY_TYPE_A, capabilityType);
998         assertTrue(toscaAnalyzerService
999                 .isTypeOf(capabilityDefinition, CAPABILITY_TYPE_B, serviceTemplate, toscaServiceModelMock));
1000     }
1001
1002     @Test
1003     public void testGetNodeTemplatesByTypeNodeTemplateIsEmpty() {
1004         ServiceTemplate serviceTemplate = new ServiceTemplate();
1005         serviceTemplate.setTopology_template(new TopologyTemplate());
1006
1007         assertTrue(toscaAnalyzerService.getNodeTemplatesByType(serviceTemplate, null, null).isEmpty());
1008     }
1009
1010     @Test
1011     public void testGetNodeTemplatesByTypeDifferentType() {
1012         ServiceTemplate serviceTemplate = new ServiceTemplate();
1013         serviceTemplate.setTopology_template(new TopologyTemplate());
1014         serviceTemplate.setNode_types(Collections.singletonMap("nodeType", new NodeType()));
1015
1016         NodeTemplate nodeTemplate = new NodeTemplate();
1017         nodeTemplate.setType("nodeType");
1018
1019         serviceTemplate.getTopology_template().setNode_templates(Collections.singletonMap("node1", nodeTemplate));
1020
1021         assertEquals(0, toscaAnalyzerService.getNodeTemplatesByType(
1022                 serviceTemplate, "nodeType1", new ToscaServiceModel()).size());
1023     }
1024
1025     @Test
1026     public void testGetNodeTemplatesByTypeSameType() {
1027         ServiceTemplate serviceTemplate = new ServiceTemplate();
1028         serviceTemplate.setTopology_template(new TopologyTemplate());
1029
1030         NodeTemplate nodeTemplate = new NodeTemplate();
1031         nodeTemplate.setType("nodeType");
1032
1033         serviceTemplate.getTopology_template().setNode_templates(Collections.singletonMap("node1", nodeTemplate));
1034
1035         assertEquals(1, toscaAnalyzerService.getNodeTemplatesByType(
1036                 serviceTemplate, "nodeType", new ToscaServiceModel()).size());
1037     }
1038
1039     @Test
1040     public void testFetchNodeTypeNodeTypePresent() {
1041         ServiceTemplate serviceTemplate = new ServiceTemplate();
1042         serviceTemplate.setNode_types(Collections.singletonMap("nodeType", new NodeType()));
1043
1044         Optional<NodeType> nodeType =
1045                 toscaAnalyzerService.fetchNodeType("nodeType", Collections.singletonList(serviceTemplate));
1046
1047         assertTrue(nodeType.isPresent());
1048     }
1049
1050     @Test
1051     public void testFetchNodeTypeNodeTypeAbsent() {
1052         ServiceTemplate serviceTemplate = new ServiceTemplate();
1053         serviceTemplate.setNode_types(Collections.singletonMap("nodeType", new NodeType()));
1054
1055         Optional<NodeType> nodeType =
1056                 toscaAnalyzerService.fetchNodeType("nodeTypeAbsent", Collections.singletonList(serviceTemplate));
1057
1058         assertFalse(nodeType.isPresent());
1059     }
1060
1061     @Test
1062     public void testGetFlatEntityForCapability() {
1063         ServiceTemplate serviceTemplate = new ServiceTemplate();
1064         CapabilityType capabilityType = new CapabilityType();
1065         capabilityType.setDescription("Capability");
1066         capabilityType.setVersion("1.0");
1067
1068         serviceTemplate.setCapability_types(Collections.singletonMap("capabilityTypeId", capabilityType));
1069         ToscaFlatData toscaFlatData =
1070                 toscaAnalyzerService.getFlatEntity(ToscaElementTypes.CAPABILITY_TYPE, "capabilityTypeId",
1071                         serviceTemplate, new ToscaServiceModel());
1072
1073         assertNotNull(toscaFlatData);
1074         assertEquals(ToscaElementTypes.CAPABILITY_TYPE, toscaFlatData.getElementType());
1075     }
1076
1077     @Test(expected = CoreException.class)
1078     public void testGetFlatEntityForCapabilityThrowsException() {
1079         ServiceTemplate serviceTemplate = new ServiceTemplate();
1080
1081         CapabilityType capabilityType = new CapabilityType();
1082         capabilityType.setDerived_from("tosca.capabilities.Root");
1083
1084         serviceTemplate.setCapability_types(Collections.singletonMap("capabilityTypeId", capabilityType));
1085
1086         toscaAnalyzerService.getFlatEntity(ToscaElementTypes.CAPABILITY_TYPE, "capabilityTypeId",
1087                 serviceTemplate, new ToscaServiceModel());
1088     }
1089
1090     @Test(expected = CoreException.class)
1091     public void testGetFlatEntityForCapabilityNullThrowsException() {
1092         toscaAnalyzerService.getFlatEntity(ToscaElementTypes.CAPABILITY_TYPE, "capabilityTypeId",
1093                 new ServiceTemplate(), new ToscaServiceModel());
1094     }
1095
1096     @Test
1097     public void testCreateInitSubstitutionNodeType() {
1098         ParameterDefinition parameterDefinitionInput = new ParameterDefinition();
1099         parameterDefinitionInput.setRequired(true);
1100         parameterDefinitionInput.set_default("default");
1101         parameterDefinitionInput.setConstraints(Collections.singletonList(new Constraint()));
1102         parameterDefinitionInput.setStatus(Status.SUPPORTED.getName());
1103
1104         ParameterDefinition parameterDefinitionOutput = new ParameterDefinition();
1105         parameterDefinitionOutput.setStatus(Status.SUPPORTED.getName());
1106
1107         ServiceTemplate serviceTemplate = new ServiceTemplate();
1108         serviceTemplate.setTopology_template(new TopologyTemplate());
1109         serviceTemplate.getTopology_template()
1110                 .setInputs(Collections.singletonMap("parameterDef1", parameterDefinitionInput));
1111         serviceTemplate.getTopology_template()
1112                 .setOutputs(Collections.singletonMap("parameterDef1", parameterDefinitionOutput));
1113
1114         NodeType nodeType = toscaAnalyzerService.createInitSubstitutionNodeType(serviceTemplate, "tosca.nodes.Root");
1115
1116         assertNotNull(nodeType);
1117         assertTrue(nodeType.getProperties().size() ==1
1118                         && nodeType.getAttributes().size() == 1);
1119     }
1120
1121     @Test(expected = CoreException.class)
1122     public void testGetSubstituteServiceTemplateNameThrowsException() {
1123         NodeTemplate nodeTemplate = new NodeTemplate();
1124         nodeTemplate.setDirectives(Collections.singletonList(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE));
1125
1126         toscaAnalyzerService.getSubstituteServiceTemplateName(null, nodeTemplate);
1127     }
1128
1129     @Test(expected = SdcRuntimeException.class)
1130     public void testGetFlatEntityThrowsExceptionIncorrectSwitchProvided() {
1131         toscaAnalyzerService.getFlatEntity(ToscaElementTypes.RELATIONSHIP_TYPE, null, null, null);
1132     }
1133
1134     @Test
1135     public void getFullPathFromRelativePathBackwards(){
1136         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1137         String importFile = "../ImportedServiceTemplate";
1138         ServiceTemplate mainServiceTemplate = new ServiceTemplate();
1139         ServiceTemplate importedServiceTemplate = new ServiceTemplate();
1140         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1141         toscaServiceModel.addServiceTemplate("Definitions/service/MainServiceTemplate", mainServiceTemplate);
1142         toscaServiceModel.addServiceTemplate("Definitions/ImportedServiceTemplate", importedServiceTemplate);
1143
1144         String fileNameForImport = toscaAnalyzerServiceImpl
1145                            .fetchFullFileNameForImport(importFile, null, mainServiceTemplate, toscaServiceModel);
1146         assertEquals("Definitions/ImportedServiceTemplate", fileNameForImport);
1147     }
1148
1149     @Test
1150     public void getFullPathFromRelativePathForwards(){
1151         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1152         String importFile = "services/ImportedServiceTemplate";
1153         ServiceTemplate mainServiceTemplate = new ServiceTemplate();
1154         ServiceTemplate importedServiceTemplate = new ServiceTemplate();
1155         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1156         toscaServiceModel.addServiceTemplate("Definitions/MainServiceTemplate", mainServiceTemplate);
1157         toscaServiceModel.addServiceTemplate("Definitions/services/ImportedServiceTemplate", importedServiceTemplate);
1158
1159         String fileNameForImport = toscaAnalyzerServiceImpl
1160                                            .fetchFullFileNameForImport(importFile, null, mainServiceTemplate, toscaServiceModel);
1161         assertEquals("Definitions/services/ImportedServiceTemplate", fileNameForImport);
1162     }
1163
1164     @Test
1165     public void getFullPathFromRelativePathMix(){
1166         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1167         String importFile = "../types/global/ImportedServiceTemplate";
1168         ServiceTemplate mainServiceTemplate = new ServiceTemplate();
1169         ServiceTemplate importedServiceTemplate = new ServiceTemplate();
1170         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1171         toscaServiceModel.addServiceTemplate("Definitions/services/MainServiceTemplate", mainServiceTemplate);
1172         toscaServiceModel.addServiceTemplate("Definitions/types/global/ImportedServiceTemplate", importedServiceTemplate);
1173
1174         String fileNameForImport = toscaAnalyzerServiceImpl
1175                                            .fetchFullFileNameForImport(importFile, null, mainServiceTemplate, toscaServiceModel);
1176         assertEquals("Definitions/types/global/ImportedServiceTemplate", fileNameForImport);
1177     }
1178
1179     @Test
1180     public void loadValidToscaYamlFileTest() throws Exception {
1181         String inputResourceName = "/mock/analyzerService/ServiceTemplateInterfaceInheritanceTest.yaml";
1182         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1183
1184         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1185         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1186         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1187         String fileFullName = "Definition/service.yaml";
1188         toscaAnalyzerServiceImpl
1189                 .loadToscaYamlFile(toscaServiceModel, toscaExtensionYamlUtil, uploadedFileData, fileFullName);
1190         Assert.assertNotNull(toscaServiceModel.getServiceTemplate(fileFullName));
1191     }
1192
1193     @Test
1194     public void loadInvalidToscaYamlFileTest() throws Exception {
1195         thrown.expect(CoreException.class);
1196         thrown.expectMessage(StringContains.containsString(
1197                 "Tosca file 'Definition/service.yaml' is not following TOSCA spec, can't be parsed. Related error - "));
1198         String inputResourceName = "/mock/analyzerService/invalidToscaFileTest.yml";
1199         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1200
1201         ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1202         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1203         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1204         String fileFullName = "Definition/service.yaml";
1205         toscaAnalyzerServiceImpl
1206                 .loadToscaYamlFile(toscaServiceModel, toscaExtensionYamlUtil, uploadedFileData, fileFullName);
1207     }
1208
1209     @Test
1210     public void loadValidToscaMetadataFileTest() throws Exception {
1211         String inputResourceName = "/mock/analyzerService/validTosca.meta";
1212         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1213
1214         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1215         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1216         toscaAnalyzerServiceImpl
1217                 .loadToscaMetaFile(toscaServiceModel, uploadedFileData);
1218         Assert.assertEquals("Definitions/service-Service2-template.yml",
1219                 toscaServiceModel.getEntryDefinitionServiceTemplate());
1220     }
1221
1222     @Test
1223     public void loadInvalidToscaMetadataFileTest() throws Exception {
1224         thrown.expect(CoreException.class);
1225         thrown.expectMessage("Missing data - TOSCA.meta file must include 'Entry-Definitions' data.");
1226         String inputResourceName = "/mock/analyzerService/invalidTosca.meta";
1227         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1228
1229         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1230         ToscaServiceModel toscaServiceModel = new ToscaServiceModel();
1231         toscaAnalyzerServiceImpl
1232                 .loadToscaMetaFile(toscaServiceModel, uploadedFileData);
1233     }
1234
1235     @Test
1236     public void loadToscaCsarPackageWithMetadataTest() throws Exception {
1237         String inputResourceName = "/mock/analyzerService/toscaPackageWithMetadata.csar";
1238         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1239         //InputStream toscaPackage = new ByteArrayInputStream(uploadedFileData);
1240         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1241         ToscaServiceModel toscaServiceModel = toscaAnalyzerServiceImpl.loadToscaCsarPackage(uploadedFileData);
1242         assertNotNull(toscaServiceModel);
1243         assertEquals("Definitions/service.yaml", toscaServiceModel.getEntryDefinitionServiceTemplate());
1244         assertEquals(10, toscaServiceModel.getServiceTemplates().size());
1245         assertEquals(1, toscaServiceModel.getArtifactFiles().getFiles().size());
1246     }
1247
1248     @Test
1249     public void loadToscaCsarPackageWithoutMetadataTest() throws Exception {
1250         String inputResourceName = "/mock/analyzerService/toscaPackageWithoutMetadata.csar";
1251         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1252         //InputStream toscaPackage = new ByteArrayInputStream(uploadedFileData);
1253         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1254         ToscaServiceModel toscaServiceModel = toscaAnalyzerServiceImpl.loadToscaCsarPackage(uploadedFileData);
1255         assertNotNull(toscaServiceModel);
1256         assertEquals("service.yaml", toscaServiceModel.getEntryDefinitionServiceTemplate());
1257         assertEquals(10, toscaServiceModel.getServiceTemplates().size());
1258         assertEquals(1, toscaServiceModel.getArtifactFiles().getFiles().size());
1259     }
1260
1261     @Test
1262     public void loadInvalidToscaCsarPackageWithoutEntryDefTest() throws Exception {
1263         thrown.expect(CoreException.class);
1264         thrown.expectMessage("TOSCA Entry Definition was not found");
1265         String inputResourceName = "/mock/analyzerService/toscaPackageInvalidEntryDef.csar";
1266         byte[] uploadedFileData = IOUtils.toByteArray(this.getClass().getResource(inputResourceName));
1267         //InputStream toscaPackage = new ByteArrayInputStream(uploadedFileData);
1268         ToscaAnalyzerServiceImpl toscaAnalyzerServiceImpl = new ToscaAnalyzerServiceImpl();
1269         toscaAnalyzerServiceImpl.loadToscaCsarPackage(uploadedFileData);
1270     }
1271 }
1272