Implement policy element convertion during onboarding VSP
[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.junit.Assert.assertTrue;
44 import static org.openecomp.core.converter.datatypes.Constants.globalStName;
45 import static org.openecomp.core.converter.datatypes.Constants.mainStName;
46
47 public class ToscaConverterImplTest {
48
49   private static final ToscaConverter toscaConverter = new ToscaConverterImpl();
50   private static final String VIRTUAL_LINK = "virtualLink";
51   private static final String UNBOUNDED = "UNBOUNDED";
52   private static final String BASE_DIR = "/mock/toscaConverter";
53
54
55   @Test
56   public void testConvertMainSt() throws IOException {
57     String inputFilesPath = BASE_DIR + "/convertMainSt/in";
58     String outputFilesPath = BASE_DIR + "/convertMainSt/out";
59
60     convertAndValidate(inputFilesPath, outputFilesPath);
61   }
62
63   @Test
64   public void testNodesConversion() throws IOException {
65     String inputFilesPath = BASE_DIR + "/convertCsar/in";
66     String outputFilesPath = BASE_DIR + "/convertCsar/out";
67
68     convertAndValidate(inputFilesPath, outputFilesPath);
69   }
70
71   @Test
72   public void testParameterConversion() throws IOException {
73     String inputFilesPath = BASE_DIR + "/convertParameters/in";
74     String outputFilesPath = BASE_DIR + "/convertParameters/out";
75
76     convertAndValidate(inputFilesPath, outputFilesPath);
77   }
78
79   @Test
80   public void testConversionWithInt() throws IOException {
81     String inputFilesPath = BASE_DIR + "/conversionWithInt/in";
82     String outputFilesPath = BASE_DIR + "/conversionWithInt/out";
83
84     convertAndValidate(inputFilesPath, outputFilesPath);
85   }
86
87   @Test
88   public void testOccurrencesUpperString() {
89     Object[] occurrences = buildOccurrences("0", UNBOUNDED);
90     Assert.assertEquals(occurrences[0], 0);
91     Assert.assertEquals(occurrences[1], UNBOUNDED);
92   }
93
94   @Test
95   public void testOccurrencesAsInts() {
96     Object[] occurrences = buildOccurrences("0", "1");
97     Assert.assertEquals(occurrences[0], 0);
98     Assert.assertEquals(occurrences[1], 1);
99   }
100
101   @Test
102   public void testOccurrencesAsStrings() {
103     String test = "TEST_A";
104     Object[] occurrences = buildOccurrences(UNBOUNDED, test);
105     Assert.assertEquals(occurrences[0], UNBOUNDED);
106     Assert.assertEquals(occurrences[1], test);
107   }
108
109   @Test
110   public void testOccurrencesLowerString() {
111     Object[] occurrences = buildOccurrences(UNBOUNDED, "100");
112     Assert.assertEquals(occurrences[0], UNBOUNDED);
113     Assert.assertEquals(occurrences[1], 100);
114   }
115
116   @Test
117   public void testOccurrencesEmpty() {
118     Object[] occurrences = buildOccurrences();
119     Assert.assertEquals(occurrences.length, 0);
120   }
121
122   @Test
123   public void testOccurrencesMany() {
124     String test = "TEST_B";
125     Object[] occurrences = buildOccurrences("1", "2", test);
126     Assert.assertEquals(occurrences[0], 1);
127     Assert.assertEquals(occurrences[1], 2);
128     Assert.assertEquals(occurrences[2], test);
129   }
130
131   @Test
132   public void testDefaultOccurrences() {
133     Object[] occurrences = buildOccurrences((List<String>) null);
134     Assert.assertEquals(1, occurrences[0]);
135     Assert.assertEquals(1, occurrences[1]);
136   }
137
138   @Test
139   public void testPoliciesBeenConverted() throws IOException {
140     String inputFilesPath = BASE_DIR + "/convertPolicies/in";
141     FileContentHandler fileContentHandler =
142             createFileContentHandlerFromInput(inputFilesPath);
143     ToscaServiceModel toscaServiceModel = toscaConverter.convert(fileContentHandler);
144     Optional<ServiceTemplate> st = toscaServiceModel.getServiceTemplate("MainServiceTemplate.yaml");
145
146     assertTrue(st.isPresent());
147
148     Map<String, PolicyDefinition> pds = st.get().getTopology_template().getPolicies();
149
150     assertEquals(2, pds.size());
151     assertTrue(pds.containsKey("scaling_aspects"));
152     assertTrue(pds.containsKey("instantiation_levels"));
153   }
154
155   private Object[] buildOccurrences(String... bounds) {
156     return buildOccurrences(Arrays.asList(bounds));
157   }
158
159   private void convertAndValidate(String inputFilesPath, String outputFilesPath)
160       throws IOException {
161     FileContentHandler fileContentHandler =
162         createFileContentHandlerFromInput(inputFilesPath);
163
164     ToscaServiceModel toscaServiceModel = toscaConverter.convert(fileContentHandler);
165     validateConvertorOutput(outputFilesPath, toscaServiceModel);
166   }
167
168   private void validateConvertorOutput(String outputFilesPath, ToscaServiceModel toscaServiceModel)
169       throws IOException {
170     ServiceTemplate mainSt = toscaServiceModel.getServiceTemplates().get(mainStName);
171     Map<String, ServiceTemplate> expectedOutserviceTemplates = new HashMap<>();
172     loadServiceTemplates(outputFilesPath, new ToscaExtensionYamlUtil(),
173         expectedOutserviceTemplates);
174
175     checkSTResults(expectedOutserviceTemplates, null, mainSt);
176   }
177
178   private Object[] buildOccurrences(List<String> bounds) {
179     NodeType nodeType = JsonUtil.json2Object("{derived_from=tosca.nodes.Root, description=MME_VFC, " +
180             "properties={vendor={type=string, default=ERICSSON}, " +
181             "csarVersion={type=string, default=v1.0}, csarProvider={type=string, default=ERICSSON}, " +
182             "id={type=string, default=vMME}, version={type=string, default=v1.0}, csarType={type=string, default=NFAR}}, " +
183             "requirements=[{virtualLink={" +
184             (bounds == null ? "" : "occurrences=[" + String.join(", ", bounds) +   "], ") +
185             "capability=tosca.capabilities.network.Linkable}}]}", NodeType.class);
186     List<Map<String, RequirementDefinition>> requirements = nodeType.getRequirements();
187     return requirements.get(0).get(VIRTUAL_LINK).getOccurrences();
188   }
189
190   private FileContentHandler createFileContentHandlerFromInput(String inputFilesPath)
191       throws IOException {
192     URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
193     String path = inputFilesUrl.getPath();
194     File directory = new File(path);
195     File[] listFiles = directory.listFiles();
196
197     FileContentHandler fileContentHandler = new FileContentHandler();
198     insertFilesIntoFileContentHandler(listFiles, fileContentHandler);
199     return fileContentHandler;
200   }
201
202   private void insertFilesIntoFileContentHandler(File[] listFiles,
203                                                  FileContentHandler fileContentHandler)
204       throws IOException {
205     byte[] fileContent;
206     if(CollectionUtils.isEmpty(fileContentHandler.getFileList())) {
207       fileContentHandler.setFiles(new HashMap<>());
208     }
209
210     for (File file : listFiles) {
211       if(!file.isDirectory()) {
212         try (FileInputStream fis = new FileInputStream(file)) {
213           fileContent = FileUtils.toByteArray(fis);
214           fileContentHandler.addFile(file.getPath(), fileContent);
215         }
216       }else{
217         File[] currFileList = file.listFiles();
218         insertFilesIntoFileContentHandler(currFileList, fileContentHandler);
219       }
220
221     }
222   }
223
224   private void checkSTResults(
225       Map<String, ServiceTemplate> expectedOutserviceTemplates,
226       ServiceTemplate gloablSubstitutionServiceTemplate, ServiceTemplate mainServiceTemplate) {
227     YamlUtil yamlUtil = new YamlUtil();
228     if (Objects.nonNull(gloablSubstitutionServiceTemplate)) {
229       assertEquals("difference global substitution service template: ",
230           yamlUtil.objectToYaml(expectedOutserviceTemplates.get(globalStName)),
231           yamlUtil.objectToYaml(gloablSubstitutionServiceTemplate));
232     }
233     if (Objects.nonNull(mainServiceTemplate)) {
234       assertEquals("difference main service template: ",
235           yamlUtil.objectToYaml(expectedOutserviceTemplates.get(mainStName)),
236           yamlUtil.objectToYaml(mainServiceTemplate));
237     }
238   }
239
240   public static void loadServiceTemplates(String serviceTemplatesPath,
241                                           ToscaExtensionYamlUtil toscaExtensionYamlUtil,
242                                           Map<String, ServiceTemplate> serviceTemplates)
243       throws IOException {
244     URL urlFile = ToscaConverterImplTest.class.getResource(serviceTemplatesPath);
245     if (urlFile != null) {
246       File pathFile = new File(urlFile.getFile());
247       File[] files = pathFile.listFiles();
248       if (files != null) {
249         addServiceTemplateFiles(serviceTemplates, files, toscaExtensionYamlUtil);
250       } else {
251         throw new NotDirectoryException(serviceTemplatesPath);
252       }
253     } else {
254       throw new NotDirectoryException(serviceTemplatesPath);
255     }
256   }
257
258   private static void addServiceTemplateFiles(Map<String, ServiceTemplate> serviceTemplates,
259                                               File[] files,
260                                               ToscaExtensionYamlUtil toscaExtensionYamlUtil) throws IOException {
261
262     for (File file : files) {
263
264       try (InputStream yamlFile = new FileInputStream(file)) {
265         ServiceTemplate serviceTemplateFromYaml =
266             toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
267         createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil);
268         serviceTemplates.put(file.getName(), serviceTemplateFromYaml);
269       }
270     }
271   }
272
273   private static void createConcreteRequirementObjectsInServiceTemplate(ServiceTemplate
274                                                                             serviceTemplateFromYaml,
275                                                                         ToscaExtensionYamlUtil
276                                                                             toscaExtensionYamlUtil) {
277
278     if (serviceTemplateFromYaml == null
279         || serviceTemplateFromYaml.getTopology_template() == null
280         || serviceTemplateFromYaml.getTopology_template().getNode_templates() == null) {
281       return;
282     }
283
284     //Creating concrete objects
285     Map<String, NodeTemplate> nodeTemplates =
286         serviceTemplateFromYaml.getTopology_template().getNode_templates();
287     for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
288       NodeTemplate nodeTemplate = entry.getValue();
289       List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
290       List<Map<String, RequirementAssignment>> concreteRequirementList = new ArrayList<>();
291       if (requirements != null) {
292         ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
293             .listIterator();
294         while (reqListIterator.hasNext()){
295           Map<String, RequirementAssignment> requirement = reqListIterator.next();
296           Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
297           for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
298             RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil
299                 .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
300                     RequirementAssignment.class));
301             concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
302             concreteRequirementList.add(concreteRequirement);
303             reqListIterator.remove();
304           }
305         }
306         requirements.clear();
307         requirements.addAll(concreteRequirementList);
308         nodeTemplate.setRequirements(requirements);
309       }
310       System.out.println();
311       //toscaExtensionYamlUtil.yamlToObject(nodeTemplate, NodeTemplate.class);
312     }
313   }
314 }