10c40282edc99d860b9e7a2cf8b2604a46811f27
[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.types.LoggerConstants;
39 import org.openecomp.sdc.logging.types.LoggerErrorCode;
40 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
41 import org.openecomp.sdc.tosca.services.ToscaFileOutputService;
42 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
43 import org.openecomp.sdc.translator.TestUtils;
44 import org.togglz.testing.TestFeatureManager;
45 import org.togglz.testing.TestFeatureManagerProvider;
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 import static org.junit.Assert.assertEquals;
62
63
64 public class BaseFullTranslationTest {
65
66   public static final String IN_POSTFIX = "/in";
67   public static final String OUT_POSTFIX = "/out";
68
69   protected static TestFeatureManager manager;
70
71   @BeforeClass
72   public static void enableForwarderFeature(){
73     manager = new TestFeatureManager(ToggleableFeature.class);
74     if (!ToggleableFeature.FORWARDER_CAPABILITY.isActive()) {
75       manager.enable(ToggleableFeature.FORWARDER_CAPABILITY);
76     }
77   }
78
79
80   @AfterClass
81   public static void disableForwarderFeature() {
82     manager.disable(ToggleableFeature.FORWARDER_CAPABILITY);
83     manager = null;
84     TestFeatureManagerProvider.setFeatureManager(null);
85   }
86
87   protected void testTranslationWithInit(String path) throws IOException {
88     File translatedZipFile = initTranslatorAndTranslate(path);
89     testTranslation(path, translatedZipFile);
90   }
91
92   protected File initTranslatorAndTranslate(String path) throws IOException {
93     HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
94     return translateZipFile(path, heatToToscaTranslator);
95   }
96
97   protected void testTranslation(String basePath, File translatedZipFile) throws IOException {
98
99     URL url = BaseFullTranslationTest.class.getResource(basePath + OUT_POSTFIX);
100     Set<String> expectedResultFileNameSet = new HashSet<>();
101     Map<String, byte[]> expectedResultMap = new HashMap<>();
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(String basePath, HeatToToscaTranslator heatToToscaTranslator) throws IOException {
141     URL inputFilesUrl = this.getClass().getResource(basePath + IN_POSTFIX);
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       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
150           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
151           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
152     }
153
154     File file = new File(path + "/VSP.zip");
155     file.createNewFile();
156
157     try (FileOutputStream fos = new FileOutputStream(file)) {
158       ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
159       fos.write(
160           toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
161     }
162
163     return file;
164   }
165
166   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
167     StringBuilder sb = new StringBuilder();
168     errorMessages.entrySet().forEach(
169         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
170             .append(getErrorList(entry.getValue())));
171
172     return sb.toString();
173   }
174
175   private String getErrorList(List<ErrorMessage> errors) {
176     StringBuilder sb = new StringBuilder();
177     errors.forEach(
178         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
179             .append(System.lineSeparator()));
180     return sb.toString();
181   }
182
183 }