Implement PNFD Model driven conversion
[sdc.git] / openecomp-be / lib / openecomp-tosca-converter-lib / openecomp-tosca-converter-core / src / test / java / org / openecomp / core / impl / ToscaConverterImplTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
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  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.core.impl;
21
22 import org.apache.commons.collections.CollectionUtils;
23 import org.junit.Assert;
24 import org.junit.Test;
25 import org.onap.sdc.tosca.datatypes.model.*;
26 import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
27 import org.onap.sdc.tosca.services.YamlUtil;
28 import org.openecomp.core.converter.ToscaConverter;
29 import org.openecomp.core.utilities.file.FileContentHandler;
30 import org.openecomp.core.utilities.file.FileUtils;
31 import org.openecomp.core.utilities.json.JsonUtil;
32 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
33
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.net.URL;
39 import java.nio.file.NotDirectoryException;
40 import java.util.*;
41
42 import static org.junit.Assert.assertEquals;
43 import static org.openecomp.core.converter.datatypes.Constants.globalStName;
44 import static org.openecomp.core.converter.datatypes.Constants.mainStName;
45
46 public class ToscaConverterImplTest {
47
48   private static final ToscaConverter toscaConverter = new ToscaConverterImpl();
49   private static final String VIRTUAL_LINK = "virtualLink";
50   private static final String UNBOUNDED = "UNBOUNDED";
51   private static final String BASE_DIR = "/mock/toscaConverter";
52
53
54   @Test
55   public void testConvertMainSt() throws IOException {
56     String inputFilesPath = BASE_DIR + "/convertMainSt/in";
57     String outputFilesPath = BASE_DIR + "/convertMainSt/out";
58
59     convertAndValidate(inputFilesPath, outputFilesPath);
60   }
61
62   @Test
63   public void testNodesConversion() throws IOException {
64     String inputFilesPath = BASE_DIR + "/convertCsar/in";
65     String outputFilesPath = BASE_DIR + "/convertCsar/out";
66
67     convertAndValidate(inputFilesPath, outputFilesPath);
68   }
69
70   @Test
71   public void testParameterConversion() throws IOException {
72     String inputFilesPath = BASE_DIR + "/convertParameters/in";
73     String outputFilesPath = BASE_DIR + "/convertParameters/out";
74
75     convertAndValidate(inputFilesPath, outputFilesPath);
76   }
77
78   @Test
79   public void testConversionWithInt() throws IOException {
80     String inputFilesPath = BASE_DIR + "/conversionWithInt/in";
81     String outputFilesPath = BASE_DIR + "/conversionWithInt/out";
82
83     convertAndValidate(inputFilesPath, outputFilesPath);
84   }
85
86   @Test
87   public void testOccurrencesUpperString() {
88     Object[] occurrences = buildOccurrences("0", UNBOUNDED);
89     Assert.assertEquals(occurrences[0], 0);
90     Assert.assertEquals(occurrences[1], UNBOUNDED);
91   }
92
93   @Test
94   public void testOccurrencesAsInts() {
95     Object[] occurrences = buildOccurrences("0", "1");
96     Assert.assertEquals(occurrences[0], 0);
97     Assert.assertEquals(occurrences[1], 1);
98   }
99
100   @Test
101   public void testOccurrencesAsStrings() {
102     String test = "TEST_A";
103     Object[] occurrences = buildOccurrences(UNBOUNDED, test);
104     Assert.assertEquals(occurrences[0], UNBOUNDED);
105     Assert.assertEquals(occurrences[1], test);
106   }
107
108   @Test
109   public void testOccurrencesLowerString() {
110     Object[] occurrences = buildOccurrences(UNBOUNDED, "100");
111     Assert.assertEquals(occurrences[0], UNBOUNDED);
112     Assert.assertEquals(occurrences[1], 100);
113   }
114
115   @Test
116   public void testOccurrencesEmpty() {
117     Object[] occurrences = buildOccurrences();
118     Assert.assertEquals(occurrences.length, 0);
119   }
120
121   @Test
122   public void testOccurrencesMany() {
123     String test = "TEST_B";
124     Object[] occurrences = buildOccurrences("1", "2", test);
125     Assert.assertEquals(occurrences[0], 1);
126     Assert.assertEquals(occurrences[1], 2);
127     Assert.assertEquals(occurrences[2], test);
128   }
129
130   @Test
131   public void testDefaultOccurrences() {
132     Object[] occurrences = buildOccurrences((List<String>) null);
133     Assert.assertEquals(1, occurrences[0]);
134     Assert.assertEquals(1, occurrences[1]);
135   }
136
137   private Object[] buildOccurrences(String... bounds) {
138     return buildOccurrences(Arrays.asList(bounds));
139   }
140
141   private void convertAndValidate(String inputFilesPath, String outputFilesPath)
142       throws IOException {
143     FileContentHandler fileContentHandler =
144         createFileContentHandlerFromInput(inputFilesPath);
145
146     ToscaServiceModel toscaServiceModel = toscaConverter.convert(fileContentHandler);
147     validateConvertorOutput(outputFilesPath, toscaServiceModel);
148   }
149
150   private void validateConvertorOutput(String outputFilesPath, ToscaServiceModel toscaServiceModel)
151       throws IOException {
152     ServiceTemplate mainSt = toscaServiceModel.getServiceTemplates().get(mainStName);
153     Map<String, ServiceTemplate> expectedOutserviceTemplates = new HashMap<>();
154     loadServiceTemplates(outputFilesPath, new ToscaExtensionYamlUtil(),
155         expectedOutserviceTemplates);
156
157     checkSTResults(expectedOutserviceTemplates, null, mainSt);
158   }
159
160   private Object[] buildOccurrences(List<String> bounds) {
161     NodeType nodeType = JsonUtil.json2Object("{derived_from=tosca.nodes.Root, description=MME_VFC, " +
162             "properties={vendor={type=string, default=ERICSSON}, " +
163             "csarVersion={type=string, default=v1.0}, csarProvider={type=string, default=ERICSSON}, " +
164             "id={type=string, default=vMME}, version={type=string, default=v1.0}, csarType={type=string, default=NFAR}}, " +
165             "requirements=[{virtualLink={" +
166             (bounds == null ? "" : "occurrences=[" + String.join(", ", bounds) +   "], ") +
167             "capability=tosca.capabilities.network.Linkable}}]}", NodeType.class);
168     List<Map<String, RequirementDefinition>> requirements = nodeType.getRequirements();
169     return requirements.get(0).get(VIRTUAL_LINK).getOccurrences();
170   }
171
172   private FileContentHandler createFileContentHandlerFromInput(String inputFilesPath)
173       throws IOException {
174     URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
175     String path = inputFilesUrl.getPath();
176     File directory = new File(path);
177     File[] listFiles = directory.listFiles();
178
179     FileContentHandler fileContentHandler = new FileContentHandler();
180     insertFilesIntoFileContentHandler(listFiles, fileContentHandler);
181     return fileContentHandler;
182   }
183
184   private void insertFilesIntoFileContentHandler(File[] listFiles,
185                                                  FileContentHandler fileContentHandler)
186       throws IOException {
187     byte[] fileContent;
188     if(CollectionUtils.isEmpty(fileContentHandler.getFileList())) {
189       fileContentHandler.setFiles(new HashMap<>());
190     }
191
192     for (File file : listFiles) {
193       if(!file.isDirectory()) {
194         try (FileInputStream fis = new FileInputStream(file)) {
195           fileContent = FileUtils.toByteArray(fis);
196           fileContentHandler.addFile(file.getPath(), fileContent);
197         }
198       }else{
199         File[] currFileList = file.listFiles();
200         insertFilesIntoFileContentHandler(currFileList, fileContentHandler);
201       }
202
203     }
204   }
205
206   private void checkSTResults(
207       Map<String, ServiceTemplate> expectedOutserviceTemplates,
208       ServiceTemplate gloablSubstitutionServiceTemplate, ServiceTemplate mainServiceTemplate) {
209     YamlUtil yamlUtil = new YamlUtil();
210     if (Objects.nonNull(gloablSubstitutionServiceTemplate)) {
211       assertEquals("difference global substitution service template: ",
212           yamlUtil.objectToYaml(expectedOutserviceTemplates.get(globalStName)),
213           yamlUtil.objectToYaml(gloablSubstitutionServiceTemplate));
214     }
215     if (Objects.nonNull(mainServiceTemplate)) {
216       assertEquals("difference main service template: ",
217           yamlUtil.objectToYaml(expectedOutserviceTemplates.get(mainStName)),
218           yamlUtil.objectToYaml(mainServiceTemplate));
219     }
220   }
221
222   public static void loadServiceTemplates(String serviceTemplatesPath,
223                                           ToscaExtensionYamlUtil toscaExtensionYamlUtil,
224                                           Map<String, ServiceTemplate> serviceTemplates)
225       throws IOException {
226     URL urlFile = ToscaConverterImplTest.class.getResource(serviceTemplatesPath);
227     if (urlFile != null) {
228       File pathFile = new File(urlFile.getFile());
229       File[] files = pathFile.listFiles();
230       if (files != null) {
231         addServiceTemplateFiles(serviceTemplates, files, toscaExtensionYamlUtil);
232       } else {
233         throw new NotDirectoryException(serviceTemplatesPath);
234       }
235     } else {
236       throw new NotDirectoryException(serviceTemplatesPath);
237     }
238   }
239
240   private static void addServiceTemplateFiles(Map<String, ServiceTemplate> serviceTemplates,
241                                               File[] files,
242                                               ToscaExtensionYamlUtil toscaExtensionYamlUtil) throws IOException {
243
244     for (File file : files) {
245
246       try (InputStream yamlFile = new FileInputStream(file)) {
247         ServiceTemplate serviceTemplateFromYaml =
248             toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
249         createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil);
250         serviceTemplates.put(file.getName(), serviceTemplateFromYaml);
251       }
252     }
253   }
254
255   private static void createConcreteRequirementObjectsInServiceTemplate(ServiceTemplate
256                                                                             serviceTemplateFromYaml,
257                                                                         ToscaExtensionYamlUtil
258                                                                             toscaExtensionYamlUtil) {
259
260     if (serviceTemplateFromYaml == null
261         || serviceTemplateFromYaml.getTopology_template() == null
262         || serviceTemplateFromYaml.getTopology_template().getNode_templates() == null) {
263       return;
264     }
265
266     //Creating concrete objects
267     Map<String, NodeTemplate> nodeTemplates =
268         serviceTemplateFromYaml.getTopology_template().getNode_templates();
269     for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
270       NodeTemplate nodeTemplate = entry.getValue();
271       List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
272       List<Map<String, RequirementAssignment>> concreteRequirementList = new ArrayList<>();
273       if (requirements != null) {
274         ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
275             .listIterator();
276         while (reqListIterator.hasNext()){
277           Map<String, RequirementAssignment> requirement = reqListIterator.next();
278           Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
279           for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
280             RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil
281                 .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
282                     RequirementAssignment.class));
283             concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
284             concreteRequirementList.add(concreteRequirement);
285             reqListIterator.remove();
286           }
287         }
288         requirements.clear();
289         requirements.addAll(concreteRequirementList);
290         nodeTemplate.setRequirements(requirements);
291       }
292       System.out.println();
293       //toscaExtensionYamlUtil.yamlToObject(nodeTemplate, NodeTemplate.class);
294     }
295   }
296 }