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