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