Code coverage using JaCoCO
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / att-sdc-translator-impl / src / test / java / com / att / sdc / translator / services / heattotosca / impl / resourcetranslation / BaseResourceTranslationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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 com.att.sdc.translator.services.heattotosca.impl.resourcetranslation;
22
23 import org.apache.commons.collections4.MapUtils;
24 import org.junit.Assert;
25 import org.junit.Before;
26 import org.openecomp.core.translator.datatypes.TranslatorOutput;
27 import org.openecomp.core.utilities.file.FileUtils;
28 import org.openecomp.core.utilities.json.JsonUtil;
29 import org.openecomp.core.validation.util.MessageContainerUtil;
30 import org.openecomp.sdc.common.errors.CoreException;
31 import org.openecomp.sdc.common.errors.ErrorCategory;
32 import org.openecomp.sdc.common.errors.ErrorCode;
33 import org.openecomp.sdc.common.utils.SdcCommon;
34 import org.openecomp.sdc.datatypes.error.ErrorLevel;
35 import org.openecomp.sdc.datatypes.error.ErrorMessage;
36 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
37 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
38 import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile;
39 import org.openecomp.sdc.logging.api.Logger;
40 import org.openecomp.sdc.logging.api.LoggerFactory;
41 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
42 import org.openecomp.sdc.logging.types.LoggerConstants;
43 import org.openecomp.sdc.logging.types.LoggerErrorCode;
44 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
45 import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition;
46 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
47 import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil;
48 import org.openecomp.sdc.tosca.services.ToscaFileOutputService;
49 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
50 import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
51 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData;
52 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData;
53 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData;
54 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData;
55 import org.openecomp.sdc.translator.services.heattotosca.TranslationService;
56
57 import java.io.BufferedInputStream;
58 import java.io.File;
59 import java.io.FileInputStream;
60 import java.io.FileOutputStream;
61 import java.io.IOException;
62 import java.net.URL;
63 import java.util.HashMap;
64 import java.util.HashSet;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.Set;
68 import java.util.zip.ZipEntry;
69 import java.util.zip.ZipInputStream;
70
71 import static org.junit.Assert.assertEquals;
72
73
74 public class BaseResourceTranslationTest {
75
76   protected String inputFilesPath;
77   protected String outputFilesPath;
78   protected TranslationContext translationContext;
79
80   private String zipFilename = "VSP.zip";
81   private TranslationService translationService;
82   private boolean isValid;
83   private File translatedZipFile;
84
85   private Map<String, byte[]> expectedResultMap = new HashMap<>();
86   private Set<String> expectedResultFileNameSet = new HashSet<>();
87
88   private final String MANIFEST_NAME = SdcCommon.MANIFEST_NAME;
89   private String validationFilename = "validationOutput.json";
90
91   //private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName());
92
93   @Before
94   public void setUp() throws IOException {
95     initTranslatorAndTranslate();
96   }
97
98   protected void initTranslatorAndTranslate() throws IOException {
99     translationService = new TranslationService();
100     translationContext = new TranslationContext();
101     translatedZipFile = translateZipFile();
102   }
103
104   protected void testTranslation() throws IOException {
105
106     URL url = BaseResourceTranslationTest.class.getResource(outputFilesPath);
107
108     String path = url.getPath();
109     File pathFile = new File(path);
110     File[] files = pathFile.listFiles();
111     Assert.assertNotNull("manifest files is empty", files);
112     for (File expectedFile : files) {
113       expectedResultFileNameSet.add(expectedFile.getName());
114       try (FileInputStream input = new FileInputStream(expectedFile)) {
115         expectedResultMap.put(expectedFile.getName(), FileUtils.toByteArray(input));
116       }
117     }
118
119     try (FileInputStream fis = new FileInputStream(translatedZipFile);
120          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
121       ZipEntry entry;
122       String name;
123       String expected;
124       String actual;
125
126       while ((entry = zis.getNextEntry()) != null) {
127
128         name = entry.getName()
129             .substring(entry.getName().lastIndexOf(File.separator) + 1, entry.getName().length());
130         if (expectedResultFileNameSet.contains(name)) {
131           expected = new String(expectedResultMap.get(name)).trim().replace("\r", "");
132           actual = new String(FileUtils.toByteArray(zis)).trim().replace("\r", "");
133           assertEquals("difference in file: " + name, expected, actual);
134
135           expectedResultFileNameSet.remove(name);
136         }
137       }
138       if (expectedResultFileNameSet.isEmpty()) {
139         expectedResultFileNameSet.forEach(System.out::println);
140       }
141     }
142     assertEquals(0, expectedResultFileNameSet.size());
143   }
144
145   private File translateZipFile() throws IOException {
146     URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
147     String path = inputFilesUrl.getPath();
148     addFilesToTranslator(translationContext, path);
149     TranslatorOutput translatorOutput = translationService.translateHeatFiles(translationContext);
150     Assert.assertNotNull(translatorOutput);
151     if (MapUtils.isNotEmpty(translatorOutput.getErrorMessages()) && MapUtils.isNotEmpty(
152         MessageContainerUtil
153             .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()))) {
154       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
155           LoggerTragetServiceName.VALIDATE_HEAT_BEFORE_TRANSLATE, ErrorLevel.ERROR.name(),
156           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't translate HEAT file");
157       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
158           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
159           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
160     }
161     File file = new File(path + "/" + zipFilename);
162     file.createNewFile();
163
164     try (FileOutputStream fos = new FileOutputStream(file)) {
165       ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
166       fos.write(
167           toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
168     }
169
170     return file;
171   }
172
173   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
174     StringBuilder sb = new StringBuilder();
175     errorMessages.entrySet().forEach(
176         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
177             .append(getErrorList(entry.getValue())));
178
179     return sb.toString();
180   }
181
182   private String getErrorList(List<ErrorMessage> errors) {
183     StringBuilder sb = new StringBuilder();
184     errors.forEach(
185         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
186             .append(System.lineSeparator()));
187     return sb.toString();
188   }
189
190   public void addFilesToTranslator(TranslationContext translationContext, String path)
191       throws IOException {
192     File manifestFile = new File(path);
193     File[] files = manifestFile.listFiles();
194     byte[] fileContent;
195
196     Assert.assertNotNull("manifest files is empty", files);
197
198     for (File file : files) {
199
200       try (FileInputStream fis = new FileInputStream(file)) {
201
202         fileContent = FileUtils.toByteArray(fis);
203
204         if (file.getName().equals(MANIFEST_NAME)) {
205           addManifest(translationContext, MANIFEST_NAME, fileContent);
206         } else {
207           if (!file.getName().equals(zipFilename) && (!file.getName().equals(validationFilename))) {
208             addFile(translationContext, file.getName(), fileContent);
209           }
210         }
211       }
212     }
213   }
214
215   public static void addManifest(TranslationContext translationContext,
216                                  String name, byte[] content) {
217     ManifestContent manifestData = JsonUtil.json2Object(new String(content), ManifestContent.class);
218     ManifestFile manifest = new ManifestFile();
219     manifest.setName(name);
220     manifest.setContent(manifestData);
221     translationContext.setManifest(manifest);
222     translationContext.addFile(name, content);
223     addFilesFromManifestToTranslationContextManifestFilesMap(translationContext, manifestData
224         .getData());
225   }
226
227   public static void addFile(TranslationContext translationContext,
228                              String name, byte[] content) {
229     translationContext.addFile(name, content);
230   }
231
232
233   public void validateComputeTemplateConsolidationData() {
234     ConsolidationData consolidationData = translationContext.getConsolidationData();
235     Map<String, ServiceTemplate> expectedServiceTemplateModels = getServiceTemplates
236         (outputFilesPath);
237     Assert.assertNotNull(consolidationData);
238     Assert.assertNotNull(consolidationData.getComputeConsolidationData());
239     Set<String> serviceTemplateFileNames = consolidationData.getComputeConsolidationData()
240         .getAllServiceTemplateFileNames();
241     Assert.assertNotNull(serviceTemplateFileNames);
242     for(String serviceTemplateName : serviceTemplateFileNames){
243       Assert.assertTrue(expectedServiceTemplateModels.containsKey(serviceTemplateName));
244       ServiceTemplate expectedServiceTemplate = expectedServiceTemplateModels.get
245           (serviceTemplateName);
246       FileComputeConsolidationData fileComputeConsolidationData = consolidationData
247           .getComputeConsolidationData().getFileComputeConsolidationData(serviceTemplateName);
248       Assert.assertNotNull(fileComputeConsolidationData);
249       Set<String> computeTypes = fileComputeConsolidationData.getAllComputeTypes();
250       Assert.assertNotNull(computeTypes);
251       for(String computeType : computeTypes) {
252         TypeComputeConsolidationData typeComputeConsolidationData = fileComputeConsolidationData
253             .getTypeComputeConsolidationData(computeType);
254         Assert.assertNotNull(typeComputeConsolidationData);
255
256         Set<String> computeNodeTemplateIds = typeComputeConsolidationData
257             .getAllComputeNodeTemplateIds();
258         Assert.assertNotNull(computeNodeTemplateIds);
259         Assert.assertNotEquals(computeNodeTemplateIds.size(), 0);
260
261         for(String computeNodeTemplateId : computeNodeTemplateIds) {
262           ComputeTemplateConsolidationData computeTemplateConsolidationData =
263               typeComputeConsolidationData.getComputeTemplateConsolidationData
264                   (computeNodeTemplateId);
265           validateGroupsInConsolidationData(computeNodeTemplateId,
266               computeTemplateConsolidationData, expectedServiceTemplate);
267         }
268       }
269     }
270   }
271
272   public Map<String, ServiceTemplate> getServiceTemplates(String baseDirPath){
273     Map<String, ServiceTemplate> serviceTemplateMap = new HashMap<>();
274     ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
275     baseDirPath = "."+baseDirPath+"/";
276     try {
277       String[] fileList = {};
278       URL filesDirUrl = BaseResourceTranslationTest.class.getClassLoader().getResource(baseDirPath);
279       if (filesDirUrl != null && filesDirUrl.getProtocol().equals("file")) {
280         fileList = new File(filesDirUrl.toURI()).list();
281       } else {
282         Assert.fail("Invalid expected output files directory");
283       }
284
285       for (int i = 0; i < fileList.length; i++) {
286         URL resource = BaseResourceTranslationTest.class.getClassLoader().getResource(baseDirPath + fileList[i]);
287         ServiceTemplate serviceTemplate = FileUtils.readViaInputStream(resource,
288                 stream -> toscaExtensionYamlUtil.yamlToObject(stream, ServiceTemplate.class));
289         serviceTemplateMap.put(fileList[i], serviceTemplate);
290       }
291
292     } catch (Exception e) {
293       //log.debug("",e);
294       Assert.fail(e.getMessage());
295     }
296     return serviceTemplateMap;
297   }
298   private void validateGroupsInConsolidationData(String computeNodeTemplateId,
299                                                  ComputeTemplateConsolidationData
300                                                      computeTemplateConsolidationData,
301                                                  ServiceTemplate expectedServiceTemplate) {
302     Assert.assertNotNull(computeTemplateConsolidationData);
303     List<String> groupIds = computeTemplateConsolidationData.getGroupIds();
304     if(groupIds != null) {
305       for(String groupId : groupIds) {
306         isComputeGroupMember(expectedServiceTemplate, computeNodeTemplateId, groupId);
307       }
308     }
309   }
310
311   private void isComputeGroupMember(ServiceTemplate expectedServiceTemplate, String
312       computeNodeTemplateId, String groupId) {
313     GroupDefinition group = expectedServiceTemplate.getTopology_template().getGroups().get(groupId);
314     List<String> groupMembers = group.getMembers();
315     Assert.assertNotNull(groupMembers);
316     Assert.assertTrue(groupMembers.contains(computeNodeTemplateId));
317   }
318
319
320   private static void addFilesFromManifestToTranslationContextManifestFilesMap(TranslationContext
321                                                                                    translationContext, List<FileData> fileDataListFromManifest) {
322     for (FileData fileFromManfiest : fileDataListFromManifest) {
323       translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType());
324     }
325   }
326 }