5de07203a19340dc00bf85ce956494ab897af43c
[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() throws IOException {
81       initTranslatorAndTranslate();
82       testTranslation();
83   }
84
85   protected void initTranslatorAndTranslate() throws IOException {
86     heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
87     translatedZipFile = translateZipFile();
88   }
89
90   protected void testTranslation() throws IOException {
91
92     URL url = BaseFullTranslationTest.class.getResource(outputFilesPath);
93     expectedResultFileNameSet = new HashSet<>();
94
95     String path = url.getPath();
96     File pathFile = new File(path);
97     File[] files = pathFile.listFiles();
98     Assert.assertNotNull("manifest files is empty", files);
99     for (File expectedFile : files) {
100       expectedResultFileNameSet.add(expectedFile.getName());
101       try (FileInputStream input = new FileInputStream(expectedFile)) {
102         expectedResultMap.put(expectedFile.getName(), FileUtils.toByteArray(input));
103       }
104     }
105
106     try (FileInputStream fis = new FileInputStream(translatedZipFile);
107          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
108       ZipEntry entry;
109       String name;
110       String expected;
111       String actual;
112
113       while ((entry = zis.getNextEntry()) != null) {
114
115         name = entry.getName()
116             .substring(entry.getName().lastIndexOf(File.separator) + 1, entry.getName().length());
117         if (expectedResultFileNameSet.contains(name)) {
118           expected = new String(expectedResultMap.get(name)).trim().replace("\r", "");
119           actual = new String(FileUtils.toByteArray(zis)).trim().replace("\r", "");
120           assertEquals("difference in file: " + name, expected, actual);
121
122           expectedResultFileNameSet.remove(name);
123         }
124       }
125       if (expectedResultFileNameSet.isEmpty()) {
126         expectedResultFileNameSet.forEach(System.out::println);
127       }
128     }
129     assertEquals(0, expectedResultFileNameSet.size());
130   }
131
132   private File translateZipFile() throws IOException {
133     URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
134     String path = inputFilesUrl.getPath();
135     TestUtils.addFilesToTranslator(heatToToscaTranslator, path);
136     TranslatorOutput translatorOutput = heatToToscaTranslator.translate();
137     Assert.assertNotNull(translatorOutput);
138     if (MapUtils.isNotEmpty(translatorOutput.getErrorMessages()) && MapUtils.isNotEmpty(
139         MessageContainerUtil
140             .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()))) {
141       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
142           LoggerTragetServiceName.VALIDATE_HEAT_BEFORE_TRANSLATE, ErrorLevel.ERROR.name(),
143           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't translate HEAT file");
144       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
145           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
146           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
147     }
148     File file = new File(path + "/" + zipFilename);
149     file.createNewFile();
150
151     try (FileOutputStream fos = new FileOutputStream(file)) {
152       ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
153       fos.write(
154           toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
155     }
156
157     return file;
158   }
159
160   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
161     StringBuilder sb = new StringBuilder();
162     errorMessages.entrySet().forEach(
163         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
164             .append(getErrorList(entry.getValue())));
165
166     return sb.toString();
167   }
168
169   private String getErrorList(List<ErrorMessage> errors) {
170     StringBuilder sb = new StringBuilder();
171     errors.forEach(
172         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
173             .append(System.lineSeparator()));
174     return sb.toString();
175   }
176
177 }