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 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;
57 import java.io.BufferedInputStream;
59 import java.io.FileInputStream;
60 import java.io.FileOutputStream;
61 import java.io.IOException;
63 import java.util.HashMap;
64 import java.util.HashSet;
65 import java.util.List;
68 import java.util.zip.ZipEntry;
69 import java.util.zip.ZipInputStream;
71 import static org.junit.Assert.assertEquals;
74 public class BaseResourceTranslationTest {
76 protected String inputFilesPath;
77 protected String outputFilesPath;
78 protected TranslationContext translationContext;
80 private String zipFilename = "VSP.zip";
81 private TranslationService translationService;
82 private boolean isValid;
83 private File translatedZipFile;
85 private Map<String, byte[]> expectedResultMap = new HashMap<>();
86 private Set<String> expectedResultFileNameSet = new HashSet<>();
88 private final String MANIFEST_NAME = SdcCommon.MANIFEST_NAME;
89 private String validationFilename = "validationOutput.json";
91 //private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName());
94 public void setUp() throws IOException {
95 initTranslatorAndTranslate();
98 protected void initTranslatorAndTranslate() throws IOException {
99 translationService = new TranslationService();
100 translationContext = new TranslationContext();
101 translatedZipFile = translateZipFile();
104 protected void testTranslation() throws IOException {
106 URL url = BaseResourceTranslationTest.class.getResource(outputFilesPath);
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));
119 try (FileInputStream fis = new FileInputStream(translatedZipFile);
120 ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
126 while ((entry = zis.getNextEntry()) != null) {
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);
135 expectedResultFileNameSet.remove(name);
138 if (expectedResultFileNameSet.isEmpty()) {
139 expectedResultFileNameSet.forEach(System.out::println);
142 assertEquals(0, expectedResultFileNameSet.size());
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(
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());
161 File file = new File(path + "/" + zipFilename);
162 file.createNewFile();
164 try (FileOutputStream fos = new FileOutputStream(file)) {
165 ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
167 toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
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())));
179 return sb.toString();
182 private String getErrorList(List<ErrorMessage> errors) {
183 StringBuilder sb = new StringBuilder();
185 error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
186 .append(System.lineSeparator()));
187 return sb.toString();
190 public void addFilesToTranslator(TranslationContext translationContext, String path)
192 File manifestFile = new File(path);
193 File[] files = manifestFile.listFiles();
196 Assert.assertNotNull("manifest files is empty", files);
198 for (File file : files) {
200 try (FileInputStream fis = new FileInputStream(file)) {
202 fileContent = FileUtils.toByteArray(fis);
204 if (file.getName().equals(MANIFEST_NAME)) {
205 addManifest(translationContext, MANIFEST_NAME, fileContent);
207 if (!file.getName().equals(zipFilename) && (!file.getName().equals(validationFilename))) {
208 addFile(translationContext, file.getName(), fileContent);
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
227 public static void addFile(TranslationContext translationContext,
228 String name, byte[] content) {
229 translationContext.addFile(name, content);
233 public void validateComputeTemplateConsolidationData() {
234 ConsolidationData consolidationData = translationContext.getConsolidationData();
235 Map<String, ServiceTemplate> expectedServiceTemplateModels = getServiceTemplates
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);
256 Set<String> computeNodeTemplateIds = typeComputeConsolidationData
257 .getAllComputeNodeTemplateIds();
258 Assert.assertNotNull(computeNodeTemplateIds);
259 Assert.assertNotEquals(computeNodeTemplateIds.size(), 0);
261 for(String computeNodeTemplateId : computeNodeTemplateIds) {
262 ComputeTemplateConsolidationData computeTemplateConsolidationData =
263 typeComputeConsolidationData.getComputeTemplateConsolidationData
264 (computeNodeTemplateId);
265 validateGroupsInConsolidationData(computeNodeTemplateId,
266 computeTemplateConsolidationData, expectedServiceTemplate);
272 public Map<String, ServiceTemplate> getServiceTemplates(String baseDirPath){
273 Map<String, ServiceTemplate> serviceTemplateMap = new HashMap<>();
274 ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
275 baseDirPath = "."+baseDirPath+"/";
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();
282 Assert.fail("Invalid expected output files directory");
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);
292 } catch (Exception e) {
294 Assert.fail(e.getMessage());
296 return serviceTemplateMap;
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);
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));
320 private static void addFilesFromManifestToTranslationContextManifestFilesMap(TranslationContext
321 translationContext, List<FileData> fileDataListFromManifest) {
322 for (FileData fileFromManfiest : fileDataListFromManifest) {
323 translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType());