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