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