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