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