d35b7dcec4da3bb4f964f16940b1872014238d10
[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 org.openecomp.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.api.HeatToToscaTranslator;
29 import org.openecomp.core.translator.datatypes.TranslatorOutput;
30 import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
31 import org.openecomp.core.utilities.file.FileUtils;
32 import org.openecomp.core.validation.util.MessageContainerUtil;
33 import org.openecomp.sdc.common.errors.CoreException;
34 import org.openecomp.sdc.common.errors.ErrorCategory;
35 import org.openecomp.sdc.common.errors.ErrorCode;
36 import org.openecomp.sdc.datatypes.error.ErrorLevel;
37 import org.openecomp.sdc.datatypes.error.ErrorMessage;
38 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
39 import org.openecomp.sdc.logging.types.LoggerConstants;
40 import org.openecomp.sdc.logging.types.LoggerErrorCode;
41 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
42 import org.openecomp.sdc.tosca.services.ToscaFileOutputService;
43 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
44 import org.openecomp.sdc.translator.TestUtils;
45 import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
46
47 import java.io.BufferedInputStream;
48 import java.io.File;
49 import java.io.FileInputStream;
50 import java.io.FileOutputStream;
51 import java.io.IOException;
52 import java.net.URL;
53 import java.util.HashMap;
54 import java.util.HashSet;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.Set;
58 import java.util.zip.ZipEntry;
59 import java.util.zip.ZipInputStream;
60
61
62 public class BaseFullTranslationTest {
63
64   protected String inputFilesPath;
65   protected String outputFilesPath;
66   protected TranslationContext translationContext;
67
68   private String zipFilename = "VSP.zip";
69   private HeatToToscaTranslator heatToToscaTranslator;
70   private File translatedZipFile;
71
72   private Map<String, byte[]> expectedResultMap = new HashMap<>();
73   private Set<String> expectedResultFileNameSet = new HashSet<>();
74
75   @Before
76   public void setUp() throws IOException {
77     initTranslatorAndTranslate();
78   }
79
80   protected void testTranslationWithInit (String inputFilesPath,
81                                           String outputFilesPath) throws IOException {
82     this.inputFilesPath = inputFilesPath;
83     this.outputFilesPath = outputFilesPath;
84
85     testTranslationWithInit();
86   }
87
88   protected void testTranslationWithInit() throws IOException {
89       initTranslatorAndTranslate();
90       testTranslation();
91   }
92
93   protected void initTranslatorAndTranslate() throws IOException {
94     heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
95     translatedZipFile = translateZipFile();
96   }
97
98   protected void testTranslation() throws IOException {
99
100     URL url = BaseFullTranslationTest.class.getResource(outputFilesPath);
101     expectedResultFileNameSet = new HashSet<>();
102
103     String path = url.getPath();
104     File pathFile = new File(path);
105     File[] files = pathFile.listFiles();
106     Assert.assertNotNull("manifest files is empty", files);
107     for (File expectedFile : files) {
108       expectedResultFileNameSet.add(expectedFile.getName());
109       try (FileInputStream input = new FileInputStream(expectedFile)) {
110         expectedResultMap.put(expectedFile.getName(), FileUtils.toByteArray(input));
111       }
112     }
113
114     try (FileInputStream fis = new FileInputStream(translatedZipFile);
115          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
116       ZipEntry entry;
117       String name;
118       String expected;
119       String actual;
120
121       while ((entry = zis.getNextEntry()) != null) {
122
123         name = entry.getName()
124             .substring(entry.getName().lastIndexOf(File.separator) + 1, entry.getName().length());
125         if (expectedResultFileNameSet.contains(name)) {
126           expected = new String(expectedResultMap.get(name)).trim().replace("\r", "");
127           actual = new String(FileUtils.toByteArray(zis)).trim().replace("\r", "");
128           assertEquals("difference in file: " + name, expected, actual);
129
130           expectedResultFileNameSet.remove(name);
131         }
132       }
133       if (expectedResultFileNameSet.isEmpty()) {
134         expectedResultFileNameSet.forEach(System.out::println);
135       }
136     }
137     assertEquals(0, expectedResultFileNameSet.size());
138   }
139
140   private File translateZipFile() throws IOException {
141     URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
142     String path = inputFilesUrl.getPath();
143     TestUtils.addFilesToTranslator(heatToToscaTranslator, path);
144     TranslatorOutput translatorOutput = heatToToscaTranslator.translate();
145     Assert.assertNotNull(translatorOutput);
146     if (MapUtils.isNotEmpty(translatorOutput.getErrorMessages()) && MapUtils.isNotEmpty(
147         MessageContainerUtil
148             .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()))) {
149       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
150           LoggerTragetServiceName.VALIDATE_HEAT_BEFORE_TRANSLATE, ErrorLevel.ERROR.name(),
151           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't translate HEAT file");
152       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
153           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
154           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
155     }
156     File file = new File(path + "/" + zipFilename);
157     file.createNewFile();
158
159     try (FileOutputStream fos = new FileOutputStream(file)) {
160       ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
161       fos.write(
162           toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
163     }
164
165     return file;
166   }
167
168   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
169     StringBuilder sb = new StringBuilder();
170     errorMessages.entrySet().forEach(
171         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
172             .append(getErrorList(entry.getValue())));
173
174     return sb.toString();
175   }
176
177   private String getErrorList(List<ErrorMessage> errors) {
178     StringBuilder sb = new StringBuilder();
179     errors.forEach(
180         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
181             .append(System.lineSeparator()));
182     return sb.toString();
183   }
184
185 }