e034fb8565e1aaa91314e5b7e69ef072d8703498
[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 org.junit.Assert;
20 import org.junit.Before;
21 import org.junit.BeforeClass;
22 import org.junit.Rule;
23 import org.junit.Test;
24 import org.junit.rules.ExpectedException;
25 import org.junit.runner.RunWith;
26 import org.mockito.Mock;
27 import org.mockito.MockitoAnnotations;
28 import org.mockito.runners.MockitoJUnitRunner;
29 import org.openecomp.sdc.common.errors.CoreException;
30 import org.openecomp.sdc.tosca.TestUtil;
31 import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
32 import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
33 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
34 import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
35 import org.onap.sdc.tosca.datatypes.model.DataType;
36 import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType;
37 import org.onap.sdc.tosca.datatypes.model.DataType;
38 import org.onap.sdc.tosca.datatypes.model.Import;
39 import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType;
40 import org.onap.sdc.tosca.datatypes.model.InterfaceType;
41 import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
42 import org.onap.sdc.tosca.datatypes.model.NodeType;
43 import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
44 import org.onap.sdc.tosca.datatypes.model.PropertyDefinition;
45 import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
46 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
47 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
48 import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping;
49 import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
50 import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
51 import org.openecomp.sdc.tosca.services.ToscaConstants;
52 import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
53
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.util.ArrayList;
57 import java.util.HashMap;
58 import java.util.List;
59 import java.util.Map;
60 import java.util.Optional;
61
62 import static org.junit.Assert.assertEquals;
63 import static org.junit.Assert.assertFalse;
64 import static org.junit.Assert.assertNotNull;
65 import static org.junit.Assert.assertTrue;
66 import static org.mockito.Mockito.when;
67
68
69 /**
70  * @author Avrahamg
71  * @since July 14, 2016
72  */
73 @RunWith(MockitoJUnitRunner.class)
74 public class ToscaAnalyzerServiceImplTest {
75     /*
76     Dictionary:
77     SrvTmp: ServiceTemplate
78     NdTmp: NodeTemplate
79     NdTy: NodeType
80     */
81
82   private static ToscaAnalyzerService toscaAnalyzerService;
83   private static ToscaServiceModel toscaServiceModel;
84   @Rule
85   public ExpectedException thrown = ExpectedException.none();
86
87   @Mock
88   private NodeTemplate nodeTemplateMock;
89   @Mock
90   private ParameterDefinition parameterDefinitionMock;
91   @Mock
92   private PropertyDefinition propertyDefinitionMock;
93   @Mock
94   private InterfaceDefinitionType interfaceDefinitionMock;
95   @Mock
96   private ToscaServiceModel toscaServiceModelMock;
97
98   @BeforeClass
99   public static void onlyOnceSetUp() throws IOException {
100     toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
101     toscaServiceModel = TestUtil.loadToscaServiceModel("/mock/analyzerService/toscasubstitution/",
102         "/mock/globalServiceTemplates/", null);
103   }
104
105   @Before
106   public void init() throws IOException {
107     MockitoAnnotations.initMocks(this);
108   }
109
110   @Test
111   public void testGetFlatEntityNotFound() throws Exception {
112     thrown.expect(CoreException.class);
113     thrown.expectMessage(
114         "Entity Type 'org.openecomp.resource.vfc.notFound' or one of its derivedFrom type hierarchy, is not defined in tosca service model");
115     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
116     try (InputStream yamlFile = toscaExtensionYamlUtil
117         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
118
119       ServiceTemplate
120           serviceTemplateFromYaml =
121           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
122
123       toscaAnalyzerService
124           .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.notFound",
125               serviceTemplateFromYaml, toscaServiceModel);
126     }
127   }
128
129   @Test
130   public void testGetFlatEntityFileNotFound() throws Exception {
131     thrown.expect(CoreException.class);
132     thrown.expectMessage(
133         "Tosca file 'missingFile.yaml' was not found in tosca service model");
134     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
135     try (InputStream yamlFile = toscaExtensionYamlUtil
136         .loadYamlFileIs("/mock/analyzerService/ServiceTemplateFileNotFoundTest.yaml")) {
137
138       ServiceTemplate
139           serviceTemplateFromYaml =
140           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
141
142       toscaAnalyzerService
143           .getFlatEntity(ToscaElementTypes.NODE_TYPE,
144               "org.openecomp.resource.vfc.nodes.heat.cmaui_image",
145               serviceTemplateFromYaml, toscaServiceModel);
146     }
147   }
148
149   @Test
150   public void testGetFlatEntityNodeType() throws Exception {
151     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
152     try (InputStream yamlFile = toscaExtensionYamlUtil
153         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
154
155       ServiceTemplate
156           serviceTemplateFromYaml =
157           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
158
159       final NodeType flatEntity = (NodeType) toscaAnalyzerService
160           .getFlatEntity(ToscaElementTypes.NODE_TYPE, "org.openecomp.resource.vfc.nodes.heat" +
161               ".cmaui_image", serviceTemplateFromYaml, toscaServiceModel);
162
163       Assert.assertNotNull(flatEntity);
164       Assert.assertEquals("org.openecomp.resource.vfc.nodes.heat.nova.Server", flatEntity
165           .getDerived_from());
166       Assert.assertEquals(20, flatEntity.getProperties().size());
167       Assert.assertEquals("overridden default value",
168           flatEntity.getProperties().get("admin_pass").get_default());
169       Assert.assertEquals("REBUILD",
170           flatEntity.getProperties().get("image_update_policy").get_default());
171       Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
172     }
173   }
174
175   @Test
176   public void testGetFlatEntityDataType() throws Exception {
177     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
178     try (InputStream yamlFile = toscaExtensionYamlUtil
179         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
180
181       ServiceTemplate
182           serviceTemplateFromYaml =
183           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
184
185       final DataType flatEntity = (DataType) toscaAnalyzerService
186           .getFlatEntity(ToscaElementTypes.DATA_TYPE,
187               "org.openecomp.datatypes.heat.network.MyNewAddressPair", serviceTemplateFromYaml,
188               toscaServiceModel);
189
190       Assert.assertNotNull(flatEntity);
191       Assert.assertEquals("org.openecomp.datatypes.heat.network.MyAddressPair", flatEntity
192           .getDerived_from());
193       Assert.assertEquals(3, flatEntity.getProperties().size());
194       Assert.assertEquals("overridden default value",
195           flatEntity.getProperties().get("mac_address").get_default());
196       Assert.assertEquals(true,
197           flatEntity.getProperties().get("mac_address").getRequired());
198       Assert.assertNotNull(flatEntity.getProperties().get("new_property"));
199     }
200   }
201
202   @Test
203   public void testCalculateExposedRequirements() throws Exception {
204     Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
205     RequirementDefinition rd = new RequirementDefinition();
206     rd.setCapability("tosca.capabilities.Node");
207     rd.setNode("tosca.nodes.Root");
208     rd.setRelationship("tosca.relationships.DependsOn");
209     Object[] occurences = new Object[]{0, "UNBOUNDED"};
210     rd.setOccurrences(occurences);
211
212     RequirementDefinition rd1 = new RequirementDefinition();
213     rd.setCapability("tosca.capabilities.network.Bindable");
214     rd.setNode(null);
215     rd.setRelationship("tosca.relationships.network.BindsTo");
216     Object[] occurences1 = new Object[]{1, 1};
217     rd1.setOccurrences(occurences1);
218
219     nodeTypeRequirementDefinition.put("binding", rd1);
220     nodeTypeRequirementDefinition.put("dependency", rd);
221
222     Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
223         new HashMap<>();
224     Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
225     RequirementAssignment ra = new RequirementAssignment();
226     ra.setCapability("tosca.capabilities.network.Bindable");
227     ra.setNode("pd_server");
228     ra.setRelationship("tosca.relationships.network.BindsTo");
229     nodeTemplateRequirementsAssignment.put("binding", ra);
230
231     List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
232     nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
233
234     List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
235         .calculateExposedRequirements(nodeTypeRequirementsDefinition,
236             nodeTemplateRequirementsAssignment);
237     Assert.assertEquals(1, exposedRequirements.size());
238   }
239
240   @Test
241   public void testCalExpReqWithNullNodeInReqAssignment() throws Exception {
242     Map<String, RequirementDefinition> nodeTypeRequirementDefinition = new HashMap<>();
243     RequirementDefinition rd = new RequirementDefinition();
244     rd.setCapability("tosca.capabilities.Node");
245     rd.setNode("tosca.nodes.Root");
246     rd.setRelationship("tosca.relationships.DependsOn");
247     Object[] occurences = new Object[]{0, "UNBOUNDED"};
248     rd.setOccurrences(occurences);
249
250     RequirementDefinition rd1 = new RequirementDefinition();
251     rd.setCapability("tosca.capabilities.network.Bindable");
252     rd.setNode(null);
253     rd.setRelationship("tosca.relationships.network.BindsTo");
254     Object[] occurences1 = new Object[]{1, 1};
255     rd1.setOccurrences(occurences1);
256
257     nodeTypeRequirementDefinition.put("binding", rd1);
258     nodeTypeRequirementDefinition.put("dependency", rd);
259
260     Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
261         new HashMap<>();
262     Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
263     RequirementAssignment ra = new RequirementAssignment();
264     ra.setCapability("tosca.capabilities.network.Bindable");
265     ra.setNode(null);
266     ra.setRelationship("tosca.relationships.network.BindsTo");
267     nodeTemplateRequirementsAssignment.put("binding", ra);
268
269     List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition = new ArrayList<>();
270     nodeTypeRequirementsDefinition.add(nodeTypeRequirementDefinition);
271
272     List<Map<String, RequirementDefinition>> exposedRequirements = toscaAnalyzerService
273         .calculateExposedRequirements(nodeTypeRequirementsDefinition,
274             nodeTemplateRequirementsAssignment);
275     Assert.assertEquals(1, exposedRequirements.size());
276   }
277
278   @Test
279   public void testCalculateExposedCapabilities() throws Exception {
280     Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
281     CapabilityDefinition cd = new CapabilityDefinition();
282     cd.setType("tosca.capabilities.Scalable");
283     nodeTypeCapabilitiesDefinition.put("tosca.capabilities.network.Bindable_pd_server", cd);
284     Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
285         new HashMap<>();
286     Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment = new HashMap<>();
287     RequirementAssignment ra = new RequirementAssignment();
288     ra.setCapability("tosca.capabilities.network.Bindable");
289     ra.setNode("pd_server");
290     ra.setRelationship("tosca.relationships.network.BindsTo");
291     nodeTemplateRequirementsAssignment.put("binding", ra);
292     fullFilledRequirementsDefinition.put("pd_server", nodeTemplateRequirementsAssignment);
293     Map<String, CapabilityDefinition> exposedCapabilities =
294         toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
295             fullFilledRequirementsDefinition);
296     Assert.assertEquals(1, exposedCapabilities.size());
297   }
298
299   @Test
300   public void testIsRequirementExistsWithInvalidReqId() throws Exception {
301     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
302     try (InputStream yamlFile = toscaExtensionYamlUtil
303         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
304
305       ServiceTemplate
306           serviceTemplateFromYaml =
307           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
308
309       TestUtil.createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml,
310           toscaExtensionYamlUtil);
311
312       NodeTemplate port_0 =
313           serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
314
315       RequirementAssignment ra = new RequirementAssignment();
316       ra.setCapability("tosca.capabilities.network.Bindable");
317       ra.setNode("server_cmaui");
318       ra.setRelationship("tosca.relationships.network.BindsTo");
319
320       //Test With Empty requirementId
321       Assert.assertEquals(false,
322           toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "", ra));
323
324       //Test With valid requirementId
325       Assert.assertEquals(true,
326           toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "binding", ra));
327
328       //Test With invalid requirement assignment
329       RequirementAssignment ra1 = new RequirementAssignment();
330       ra1.setCapability("tosca.capabilities.network.Bindable1");
331       ra1.setNode("server_cmaui1");
332       ra1.setRelationship("tosca.relationships.network.BindsTo1");
333       Assert.assertEquals(false,
334           toscaAnalyzerService.isRequirementExistInNodeTemplate(port_0, "binding", ra1));
335     }
336   }
337
338   @Test
339   public void testGetRequirements() throws Exception {
340     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
341     try (InputStream yamlFile = toscaExtensionYamlUtil
342         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
343
344       ServiceTemplate
345           serviceTemplateFromYaml =
346           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
347
348       NodeTemplate port_0 =
349           serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0");
350       List<RequirementAssignment> reqList =
351           toscaAnalyzerService.getRequirements(port_0, ToscaConstants.BINDING_REQUIREMENT_ID);
352       assertEquals(1, reqList.size());
353
354       reqList.clear();
355       NodeTemplate port_1 =
356           serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1");
357       reqList = toscaAnalyzerService.getRequirements(port_1, ToscaConstants.LINK_REQUIREMENT_ID);
358       assertEquals(2, reqList.size());
359
360       reqList.clear();
361       reqList = toscaAnalyzerService.getRequirements(port_0, ToscaConstants.LINK_REQUIREMENT_ID);
362       assertEquals(0, reqList.size());
363     }
364   }
365
366   @Test
367   public void testGetNodeTemplateById() throws Exception {
368     ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
369     Optional<NodeTemplate> nodeTemplate =
370         toscaAnalyzerService.getNodeTemplateById(emptyServiceTemplate, "test_net222");
371     assertEquals(false, nodeTemplate.isPresent());
372
373     ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
374         .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
375     nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
376     assertEquals(true, nodeTemplate.isPresent());
377
378     nodeTemplate = toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net222");
379     assertEquals(false, nodeTemplate.isPresent());
380   }
381
382   @Test
383   public void testGetSubstituteServiceTemplateName() throws Exception {
384     thrown.expect(CoreException.class);
385     thrown.expectMessage(
386         "Invalid Substitute Node Template invalid2, mandatory map property service_template_filter with mandatory key substitute_service_template must be defined.");
387
388     Optional<String> substituteServiceTemplateName;
389
390     ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
391         .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
392     Optional<NodeTemplate> notSubstitutableNodeTemplate =
393         toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_net");
394     assertEquals(true, notSubstitutableNodeTemplate.isPresent());
395
396     if (notSubstitutableNodeTemplate.isPresent()) {
397       substituteServiceTemplateName = toscaAnalyzerService
398           .getSubstituteServiceTemplateName("test_net", notSubstitutableNodeTemplate.get());
399       assertEquals(false, substituteServiceTemplateName.isPresent());
400     }
401
402     Optional<NodeTemplate> substitutableNodeTemplate =
403         toscaAnalyzerService.getNodeTemplateById(mainServiceTemplate, "test_nested");
404     assertEquals(true, substitutableNodeTemplate.isPresent());
405     if (substitutableNodeTemplate.isPresent()) {
406       substituteServiceTemplateName = toscaAnalyzerService
407           .getSubstituteServiceTemplateName("test_nested", substitutableNodeTemplate.get());
408       assertEquals(true, substituteServiceTemplateName.isPresent());
409       assertEquals("nestedServiceTemplate.yaml", substituteServiceTemplateName.get());
410     }
411
412     NodeTemplate invalidSubstitutableNodeTemplate1 = new NodeTemplate();
413     substituteServiceTemplateName = toscaAnalyzerService
414         .getSubstituteServiceTemplateName("invalid1", invalidSubstitutableNodeTemplate1);
415     assertEquals(false, substituteServiceTemplateName.isPresent());
416
417     substitutableNodeTemplate.ifPresent(nodeTemplate -> {
418       Object serviceTemplateFilter = nodeTemplate.getProperties()
419           .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
420       ((Map) serviceTemplateFilter).clear();
421       toscaAnalyzerService
422           .getSubstituteServiceTemplateName("invalid2", nodeTemplate);
423
424     });
425   }
426
427
428   @Test
429   public void testGetSubstitutableNodeTemplates() throws Exception {
430     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
431     try (InputStream yamlFile = toscaExtensionYamlUtil
432         .loadYamlFileIs("/mock/analyzerService/ServiceTemplateSubstituteTest.yaml")) {
433       ServiceTemplate serviceTemplateFromYaml =
434           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
435
436       Map<String, NodeTemplate> substitutableNodeTemplates =
437           toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
438       assertEquals(2, substitutableNodeTemplates.size());
439       assertNotNull(substitutableNodeTemplates.get("test_nested1"));
440       assertNotNull(substitutableNodeTemplates.get("test_nested2"));
441
442       ServiceTemplate emptyServiceTemplate = new ServiceTemplate();
443       emptyServiceTemplate.setTopology_template(new TopologyTemplate());
444       substitutableNodeTemplates =
445           toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate);
446       assertEquals(0, substitutableNodeTemplates.size());
447     }
448
449     try (InputStream yamlFile = toscaExtensionYamlUtil
450         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
451       ServiceTemplate serviceTemplateFromYaml =
452           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
453       Map<String, NodeTemplate> substitutableNodeTemplates =
454           toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml);
455       assertEquals(0, substitutableNodeTemplates.size());
456     }
457   }
458
459   @Test
460   public void testGetSubstitutionMappedNodeTemplateByExposedReq() throws Exception {
461     thrown.expect(CoreException.class);
462     thrown.expectMessage(
463         "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
464     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
465     try (InputStream yamlFile = toscaExtensionYamlUtil
466         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
467       ServiceTemplate nestedServiceTemplateFromYaml =
468           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
469
470       Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
471           .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
472               nestedServiceTemplateFromYaml, "local_storage_server_cmaui");
473       assertEquals(true, mappedNodeTemplate.isPresent());
474       mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
475         assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
476         assertNotNull(stringNodeTemplateEntry.getValue());
477       });
478
479       mappedNodeTemplate = toscaAnalyzerService
480           .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
481               nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
482       assertEquals(true, mappedNodeTemplate.isPresent());
483       mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> {
484         assertEquals("server_cmaui", stringNodeTemplateEntry.getKey());
485         assertNotNull(stringNodeTemplateEntry.getValue());
486       });
487
488       ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
489           .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
490       mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq(
491           toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
492           "local_storage_server_cmaui");
493       assertEquals(false, mappedNodeTemplate.isPresent());
494     }
495   }
496
497   @Test
498   public void invalidSubstitutableMapping() throws Exception {
499     thrown.expect(CoreException.class);
500     thrown.expectMessage(
501         "Invalid Substitution Service Template invalidMappingServiceTemplate.yaml, missing mandatory file 'Node type' in substitution mapping.");
502     ServiceTemplate invalidMappingServiceTemplate = new ServiceTemplate();
503     invalidMappingServiceTemplate.setTopology_template(new TopologyTemplate());
504     invalidMappingServiceTemplate.getTopology_template()
505         .setSubstitution_mappings(new SubstitutionMapping());
506     toscaAnalyzerService
507         .getSubstitutionMappedNodeTemplateByExposedReq("invalidMappingServiceTemplate.yaml",
508             invalidMappingServiceTemplate, "local_storage_server_cmaui");
509   }
510
511   @Test
512   public void substitutableMappingWithNoReqMap() throws Exception {
513     ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates()
514         .get(toscaServiceModel.getEntryDefinitionServiceTemplate());
515     ServiceTemplate emptyReqMapping = new ServiceTemplate();
516     emptyReqMapping.setTopology_template(new TopologyTemplate());
517     emptyReqMapping.getTopology_template().setSubstitution_mappings(new SubstitutionMapping());
518     emptyReqMapping.getTopology_template().getSubstitution_mappings().setNode_type("temp");
519     Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService
520         .getSubstitutionMappedNodeTemplateByExposedReq(
521             toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate,
522             "local_storage_server_cmaui");
523     assertEquals(false, mappedNodeTemplate.isPresent());
524   }
525
526   @Test
527   public void testGetSubstitutionMappedNodeTemplateByExposedReqInvalid() throws Exception {
528     thrown.expect(CoreException.class);
529     thrown.expectMessage(
530         "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9");
531     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
532     try (InputStream yamlFile = toscaExtensionYamlUtil
533         .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) {
534       ServiceTemplate nestedServiceTemplateFromYaml =
535           toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
536
537       toscaAnalyzerService
538           .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml",
539               nestedServiceTemplateFromYaml, "link_cmaui_port_invalid");
540     }
541   }
542
543   @Test
544   public void testIsDesiredRequirementAssignmentMatch() throws Exception {
545
546     RequirementAssignment requirementAssignment = new RequirementAssignment();
547     String capability = "Test.Capability";
548     String node = "Test.node";
549     String relationship = "Test.relationship";
550     requirementAssignment.setCapability(capability);
551     requirementAssignment.setNode(node);
552     requirementAssignment.setRelationship(relationship);
553
554     assertEquals(true, toscaAnalyzerService
555         .isDesiredRequirementAssignment(requirementAssignment, capability, node, relationship));
556     assertEquals(true, toscaAnalyzerService
557         .isDesiredRequirementAssignment(requirementAssignment, null, node, relationship));
558     assertEquals(true, toscaAnalyzerService
559         .isDesiredRequirementAssignment(requirementAssignment, capability, null, relationship));
560     assertEquals(true, toscaAnalyzerService
561         .isDesiredRequirementAssignment(requirementAssignment, capability, node, null));
562     assertEquals(true, toscaAnalyzerService
563         .isDesiredRequirementAssignment(requirementAssignment, null, null, relationship));
564     assertEquals(true, toscaAnalyzerService
565         .isDesiredRequirementAssignment(requirementAssignment, capability, null, null));
566     assertEquals(true, toscaAnalyzerService
567         .isDesiredRequirementAssignment(requirementAssignment, null, node, null));
568
569   }
570
571   @Test
572   public void testIsDesiredRequirementAssignmentNoMatch() throws Exception {
573
574     RequirementAssignment requirementAssignment = new RequirementAssignment();
575     String capability = "Test.Capability";
576     String node = "Test.node";
577     String relationship = "Test.relationship";
578     requirementAssignment.setCapability(capability);
579     requirementAssignment.setNode(node);
580     requirementAssignment.setRelationship(relationship);
581
582     assertEquals(false, toscaAnalyzerService
583         .isDesiredRequirementAssignment(requirementAssignment, "no", node, relationship));
584     assertEquals(false, toscaAnalyzerService
585         .isDesiredRequirementAssignment(requirementAssignment, "no", "no", relationship));
586     assertEquals(false, toscaAnalyzerService
587         .isDesiredRequirementAssignment(requirementAssignment, "no", "no", "no"));
588     assertEquals(false, toscaAnalyzerService
589         .isDesiredRequirementAssignment(requirementAssignment, capability, "no", relationship));
590     assertEquals(false, toscaAnalyzerService
591         .isDesiredRequirementAssignment(requirementAssignment, capability, node, "no"));
592     assertEquals(false, toscaAnalyzerService
593         .isDesiredRequirementAssignment(requirementAssignment, capability, "no", "no"));
594     assertEquals(false, toscaAnalyzerService
595         .isDesiredRequirementAssignment(requirementAssignment, "no", null, null));
596     assertEquals(false, toscaAnalyzerService
597         .isDesiredRequirementAssignment(requirementAssignment, null, null, null));
598
599
600   }
601
602   @Test
603   public void shouldReturnFalseIfNdTmpIsNull() {
604     NodeTemplate nodeTemplate = null;
605     assertFalse(toscaAnalyzerService
606         .isTypeOf(nodeTemplate, ToscaNodeType.NATIVE_NETWORK, new ServiceTemplate(),
607             toscaServiceModelMock));
608   }
609
610   @Test
611   public void shouldReturnTrueIfNdTmpTypeIsOfRequestedType() {
612     NodeTemplate nodeTemplate = new NodeTemplate();
613     String nodeTypeToSearch = ToscaNodeType.NATIVE_BLOCK_STORAGE;
614     nodeTemplate.setType(nodeTypeToSearch);
615     assertTrue(toscaAnalyzerService
616         .isTypeOf(nodeTemplate, nodeTypeToSearch, new ServiceTemplate(),
617             toscaServiceModelMock));
618   }
619
620   @Test
621   public void shouldReturnTrueIfDataTypeIsOfRequestedType() {
622     PropertyDefinition propertyDefinition = new PropertyDefinition();
623     String propertyTypeToSearch = "tosca.datatypes.TimeInterval";
624     propertyDefinition.setType(propertyTypeToSearch);
625     assertTrue(toscaAnalyzerService
626         .isTypeOf(propertyDefinition, propertyTypeToSearch, new ServiceTemplate(),
627             toscaServiceModelMock));
628   }
629
630   @Test
631   public void shouldReturnTrueIfInterfaceTypeIsOfRequestedType() {
632     InterfaceDefinitionType interfaceDefinition = new InterfaceDefinitionType();
633     String interfaceTypeToSearch = "test.interface.A";
634     interfaceDefinition.setType(interfaceTypeToSearch);
635     assertTrue(toscaAnalyzerService
636         .isTypeOf(interfaceDefinition, interfaceTypeToSearch, new ServiceTemplate(),
637             toscaServiceModelMock));
638   }
639
640   @Test
641   public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNdTyDerivedFromRequestedType() {
642     String typeToMatch = ToscaNodeType.CINDER_VOLUME;
643     when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
644     Map<String, NodeType> stNodeTypes = new HashMap<>();
645     addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
646     NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
647     addNodeType(stNodeTypes, typeToMatch, nodeType);
648     ServiceTemplate serviceTemplate = new ServiceTemplate();
649     serviceTemplate.setNode_types(stNodeTypes);
650     assertTrue(toscaAnalyzerService
651         .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE,
652             serviceTemplate, toscaServiceModelMock));
653
654   }
655
656   @Test
657   public void dataTypeParameterExistInHierarchy() {
658     String testedDataTypeKey = "test.dataType.B";
659     when(parameterDefinitionMock.getType()).thenReturn(testedDataTypeKey);
660     dataTypeExistInHierarchy(testedDataTypeKey, parameterDefinitionMock);
661
662   }
663
664   @Test
665   public void dataTypePropertyExistInHierarchy() {
666     String testedDataTypeKey = "test.dataType.B";
667     when(propertyDefinitionMock.getType()).thenReturn(testedDataTypeKey);
668     dataTypeExistInHierarchy(testedDataTypeKey, propertyDefinitionMock);
669   }
670
671   private void dataTypeExistInHierarchy(String testedDataTypeKey,
672                                         DefinitionOfDataType testedDefinitionDataType) {
673     String typeToMatch = "test.dataType.A";
674     Map<String, DataType> stDataTypes = new HashMap<>();
675     addDataType(stDataTypes, "tosca.datatypes.network.NetworkInfo", new DataType());
676     DataType testedDataType = createDataType(typeToMatch);
677     addDataType(stDataTypes, testedDataTypeKey, testedDataType);
678     ServiceTemplate serviceTemplate = new ServiceTemplate();
679     serviceTemplate.setData_types(stDataTypes);
680     assertTrue(toscaAnalyzerService
681         .isTypeOf(testedDefinitionDataType, typeToMatch, serviceTemplate, toscaServiceModelMock));
682   }
683
684   @Test
685   public void interfaceTypeExistInHierarchy() {
686     String typeToMatch = "test.interfaceType.A";
687     String testedInterfaceTypeKey = "test.interfaceType.B";
688     when(interfaceDefinitionMock.getType()).thenReturn(testedInterfaceTypeKey);
689     Map<String, Object> stInterfaceTypes = new HashMap<>();
690     stInterfaceTypes.put("tosca.interfaces.network.NetworkInfo", new InterfaceType());
691     InterfaceType testedInterfaceType = createInterfaceType(typeToMatch);
692     stInterfaceTypes.put(testedInterfaceTypeKey, testedInterfaceType);
693     ServiceTemplate serviceTemplate = new ServiceTemplate();
694     serviceTemplate.setInterface_types(stInterfaceTypes);
695     assertTrue(toscaAnalyzerService
696         .isTypeOf(interfaceDefinitionMock, "test.interfaceType.A",
697             serviceTemplate, toscaServiceModelMock));
698   }
699
700   @Test
701   public void shouldThrowCoreExceptionForInvalidNodeType() {
702     thrown.expect(CoreException.class);
703     thrown.expectMessage(
704         "Entity Type 'AAA' or one of its derivedFrom type hierarchy, is not defined in " +
705             "tosca service model");
706     when(nodeTemplateMock.getType()).thenReturn("AAA");
707     Map<String, NodeType> stNodeTypes = new HashMap<>();
708     addNodeType(stNodeTypes, "notImportant", new NodeType());
709     ServiceTemplate serviceTemplate = new ServiceTemplate();
710     serviceTemplate.setNode_types(stNodeTypes);
711     toscaAnalyzerService
712         .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_COMPUTE, serviceTemplate,
713             toscaServiceModelMock);
714   }
715
716   @Test
717   public void shouldThrowCoreExceptionForInvalidNodeType2Level() {
718     thrown.expect(CoreException.class);
719     thrown.expectMessage(
720         "Entity Type 'A' or one of its derivedFrom type hierarchy, is not defined in tosca " +
721             "service model");
722     String typeToMatch = "A";
723     when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
724     Map<String, NodeType> stNodeTypes = new HashMap<>();
725     addNodeType(stNodeTypes, "notImportant", new NodeType());
726     addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
727     addNodeType(stNodeTypes, "ADerivedFromB'", createNodeType("BDerivedFromC"));
728     ServiceTemplate serviceTemplate = new ServiceTemplate();
729     serviceTemplate.setNode_types(stNodeTypes);
730     assertTrue(toscaAnalyzerService
731         .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
732   }
733
734   @Test
735   public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyAndNotDerivedFromRequestedTypeBut2ndLevelDerivedFromMatch() {
736     String typeToMatch = "A";
737     when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
738     Map<String, NodeType> stNodeTypes = new HashMap<>();
739     addNodeType(stNodeTypes, "notImportant", new NodeType());
740     addNodeType(stNodeTypes, "A", createNodeType("ADerivedFromB"));
741     addNodeType(stNodeTypes, "ADerivedFromB", createNodeType("BDerivedFromC"));
742     ServiceTemplate serviceTemplate = new ServiceTemplate();
743     serviceTemplate.setNode_types(stNodeTypes);
744     assertTrue(toscaAnalyzerService
745         .isTypeOf(nodeTemplateMock, "BDerivedFromC", serviceTemplate, toscaServiceModelMock));
746   }
747
748   private NodeType createNodeType(String derivedFrom) {
749     NodeType nodeType = new NodeType();
750     nodeType.setDerived_from(derivedFrom);
751     return nodeType;
752   }
753
754   private DataType createDataType(String derivedFrom) {
755     DataType dataType = new DataType();
756     dataType.setDerived_from(derivedFrom);
757     return dataType;
758   }
759
760   private InterfaceType createInterfaceType(String derivedFrom) {
761     InterfaceType interfaceType = new InterfaceType();
762     interfaceType.setDerived_from(derivedFrom);
763     return interfaceType;
764   }
765
766   private void addNodeType(Map<String, NodeType> stNodeTypes, String key, NodeType nodeType) {
767     stNodeTypes.put(key, nodeType);
768   }
769
770   private void addDataType(Map<String, DataType> stDataTypes, String key, DataType dataType) {
771     stDataTypes.put(key, dataType);
772   }
773
774   @Test
775   public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn1stLevelImports() {
776     String typeToMatch = ToscaNodeType.CINDER_VOLUME;
777     when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
778     ServiceTemplate mainST = new ServiceTemplate();
779     List<Map<String, Import>> imports = new ArrayList<>();
780     Map<String, Import> importMap = new HashMap<>();
781     Import anImport = new Import();
782     anImport.setFile("mainImport");
783     importMap.put("bla bla", anImport);
784     imports.add(importMap);
785     mainST.setImports(imports);
786
787     //create searchable service template
788     Map<String, NodeType> stNodeTypes = new HashMap<>();
789     addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
790     NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
791     addNodeType(stNodeTypes, typeToMatch, nodeType);
792     ServiceTemplate serviceTemplate = new ServiceTemplate();
793     serviceTemplate.setNode_types(stNodeTypes);
794
795     // add service templates to tosca service model
796     Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
797     serviceTemplates.put("testMainServiceTemplate", mainST);
798     serviceTemplates.put("mainImport", serviceTemplate);
799     when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
800
801     assertTrue(toscaAnalyzerService
802         .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
803             toscaServiceModelMock));
804   }
805
806   @Test
807   public void shouldReturnTrueIfNdTmpTypeIsFoundInSrvTmpNdTyButRequestedTypeNotMatchButFoundIn2ndLevelImports() {
808     String typeToMatch = ToscaNodeType.CINDER_VOLUME;
809     when(nodeTemplateMock.getType()).thenReturn(typeToMatch);
810     ServiceTemplate mainST = new ServiceTemplate();
811     List<Map<String, Import>> imports = new ArrayList<>();
812     Map<String, Import> importMap = new HashMap<>();
813     Import anImport = new Import();
814     anImport.setFile("refToMainImport");
815     importMap.put("bla bla", anImport);
816     imports.add(importMap);
817     mainST.setImports(imports);
818
819     //create searchable service template
820     Map<String, NodeType> stNodeTypes = new HashMap<>();
821     addNodeType(stNodeTypes, ToscaNodeType.NATIVE_COMPUTE, new NodeType());
822     NodeType nodeType = createNodeType(ToscaNodeType.NATIVE_BLOCK_STORAGE);
823     addNodeType(stNodeTypes, typeToMatch, nodeType);
824     ServiceTemplate serviceTemplate = new ServiceTemplate();
825     serviceTemplate.setNode_types(stNodeTypes);
826
827     // create 1st level service template with import only
828     ServiceTemplate firstLevelST = new ServiceTemplate();
829     List<Map<String, Import>> firstLevelImports = new ArrayList<>();
830     Map<String, Import> firstLevelImportsMap = new HashMap<>();
831     Import firstLevelImport = new Import();
832     firstLevelImport.setFile("mainImport");
833     firstLevelImportsMap.put("bla bla 2", firstLevelImport);
834     firstLevelImports.add(firstLevelImportsMap);
835     firstLevelST.setImports(firstLevelImports);
836
837     // add service templates to tosca service model
838     Map<String, ServiceTemplate> serviceTemplates = toscaServiceModelMock.getServiceTemplates();
839     serviceTemplates.put("testMainServiceTemplate", mainST);
840     serviceTemplates.put("refToMainImport", firstLevelST);
841     serviceTemplates.put("mainImport", serviceTemplate);
842     when(toscaServiceModelMock.getServiceTemplates()).thenReturn(serviceTemplates);
843
844     assertTrue(toscaAnalyzerService
845         .isTypeOf(nodeTemplateMock, ToscaNodeType.NATIVE_BLOCK_STORAGE, mainST,
846             toscaServiceModelMock));
847   }
848
849   // not found at all should throw core exception
850
851
852 }