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