2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package com.att.sdc.translator.services.heattotosca.impl.resourcetranslation;
23 import static org.junit.Assert.assertEquals;
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;
59 import java.io.BufferedInputStream;
61 import java.io.FileInputStream;
62 import java.io.FileOutputStream;
63 import java.io.IOException;
64 import java.io.InputStream;
66 import java.util.HashMap;
67 import java.util.HashSet;
68 import java.util.List;
71 import java.util.zip.ZipEntry;
72 import java.util.zip.ZipInputStream;
75 public class BaseResourceTranslationTest {
77 protected String inputFilesPath;
78 protected String outputFilesPath;
79 protected TranslationContext translationContext;
81 private String zipFilename = "VSP.zip";
82 private TranslationService translationService;
83 private boolean isValid;
84 private File translatedZipFile;
86 private Map<String, byte[]> expectedResultMap = new HashMap<>();
87 private Set<String> expectedResultFileNameSet = new HashSet<>();
89 private final String MANIFEST_NAME = SdcCommon.MANIFEST_NAME;
90 private String validationFilename = "validationOutput.json";
93 public void setUp() throws IOException {
94 initTranslatorAndTranslate();
97 protected void initTranslatorAndTranslate() throws IOException {
98 translationService = new TranslationService();
99 translationContext = new TranslationContext();
100 translatedZipFile = translateZipFile();
103 protected void testTranslation() throws IOException {
105 URL url = BaseResourceTranslationTest.class.getResource(outputFilesPath);
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));
118 try (FileInputStream fis = new FileInputStream(translatedZipFile);
119 ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
125 while ((entry = zis.getNextEntry()) != null) {
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);
134 expectedResultFileNameSet.remove(name);
137 if (expectedResultFileNameSet.isEmpty()) {
138 expectedResultFileNameSet.forEach(System.out::println);
141 assertEquals(0, expectedResultFileNameSet.size());
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(
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());
160 File file = new File(path + "/" + zipFilename);
161 file.createNewFile();
163 try (FileOutputStream fos = new FileOutputStream(file)) {
164 ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
166 toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
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())));
178 return sb.toString();
181 private String getErrorList(List<ErrorMessage> errors) {
182 StringBuilder sb = new StringBuilder();
184 error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
185 .append(System.lineSeparator()));
186 return sb.toString();
189 public void addFilesToTranslator(TranslationContext translationContext, String path)
191 File manifestFile = new File(path);
192 File[] files = manifestFile.listFiles();
195 Assert.assertNotNull("manifest files is empty", files);
197 for (File file : files) {
199 try (FileInputStream fis = new FileInputStream(file)) {
201 fileContent = FileUtils.toByteArray(fis);
203 if (file.getName().equals(MANIFEST_NAME)) {
204 addManifest(translationContext, MANIFEST_NAME, fileContent);
206 if (!file.getName().equals(zipFilename) && (!file.getName().equals(validationFilename))) {
207 addFile(translationContext, file.getName(), fileContent);
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
226 public static void addFile(TranslationContext translationContext,
227 String name, byte[] content) {
228 translationContext.addFile(name, content);
232 public void validateComputeTemplateConsolidationData() {
233 ConsolidationData consolidationData = translationContext.getConsolidationData();
234 Map<String, ServiceTemplate> expectedServiceTemplateModels = getServiceTemplates
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);
255 Set<String> computeNodeTemplateIds = typeComputeConsolidationData
256 .getAllComputeNodeTemplateIds();
257 Assert.assertNotNull(computeNodeTemplateIds);
258 Assert.assertNotEquals(computeNodeTemplateIds.size(), 0);
260 for(String computeNodeTemplateId : computeNodeTemplateIds) {
261 ComputeTemplateConsolidationData computeTemplateConsolidationData =
262 typeComputeConsolidationData.getComputeTemplateConsolidationData
263 (computeNodeTemplateId);
264 validateGroupsInConsolidationData(computeNodeTemplateId,
265 computeTemplateConsolidationData, expectedServiceTemplate);
271 public Map<String, ServiceTemplate> getServiceTemplates(String baseDirPath){
272 Map<String, ServiceTemplate> serviceTemplateMap = new HashMap<>();
273 ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
274 baseDirPath = "."+baseDirPath+"/";
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();
281 Assert.fail("Invalid expected output files directory");
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);
291 } catch (Exception e) {
292 Assert.fail(e.getMessage());
294 return serviceTemplateMap;
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);
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));
318 private static void addFilesFromManifestToTranslationContextManifestFilesMap(TranslationContext
319 translationContext, List<FileData> fileDataListFromManifest) {
320 for (FileData fileFromManfiest : fileDataListFromManifest) {
321 translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType());