f5e1ebbe76845cf67c9152a7facede9cb652cf51
[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.tosca.services.ToscaFileOutputService;
39 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
40 import org.openecomp.sdc.translator.TestUtils;
41 import org.togglz.testing.TestFeatureManager;
42 import org.togglz.testing.TestFeatureManagerProvider;
43
44 import java.io.BufferedInputStream;
45 import java.io.File;
46 import java.io.FileInputStream;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.net.URL;
50 import java.util.HashMap;
51 import java.util.HashSet;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Set;
55 import java.util.zip.ZipEntry;
56 import java.util.zip.ZipInputStream;
57
58 import static org.junit.Assert.assertEquals;
59
60
61 public class BaseFullTranslationTest {
62
63   public static final String IN_POSTFIX = "/in";
64   public static final String OUT_POSTFIX = "/out";
65
66   protected static TestFeatureManager manager;
67
68   @BeforeClass
69   public static void enableForwarderFeature(){
70     manager = new TestFeatureManager(ToggleableFeature.class);
71     if (!ToggleableFeature.FORWARDER_CAPABILITY.isActive()) {
72       manager.enable(ToggleableFeature.FORWARDER_CAPABILITY);
73     }
74   }
75
76
77   @AfterClass
78   public static void disableForwarderFeature() {
79     manager.disable(ToggleableFeature.FORWARDER_CAPABILITY);
80     manager = null;
81     TestFeatureManagerProvider.setFeatureManager(null);
82   }
83
84   protected void testTranslationWithInit(String path) throws IOException {
85     File translatedZipFile = initTranslatorAndTranslate(path);
86     testTranslation(path, translatedZipFile);
87   }
88
89   protected File initTranslatorAndTranslate(String path) throws IOException {
90     HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
91     return translateZipFile(path, heatToToscaTranslator);
92   }
93
94   protected void testTranslation(String basePath, File translatedZipFile) throws IOException {
95
96     URL url = BaseFullTranslationTest.class.getResource(basePath + OUT_POSTFIX);
97     Set<String> expectedResultFileNameSet = new HashSet<>();
98     Map<String, byte[]> expectedResultMap = new HashMap<>();
99
100     String path = url.getPath();
101     File pathFile = new File(path);
102     File[] files = pathFile.listFiles();
103     Assert.assertNotNull("manifest files is empty", files);
104     for (File expectedFile : files) {
105       expectedResultFileNameSet.add(expectedFile.getName());
106       try (FileInputStream input = new FileInputStream(expectedFile)) {
107         expectedResultMap.put(expectedFile.getName(), FileUtils.toByteArray(input));
108       }
109     }
110
111     try (FileInputStream fis = new FileInputStream(translatedZipFile);
112          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
113       ZipEntry entry;
114       String name;
115       String expected;
116       String actual;
117
118       while ((entry = zis.getNextEntry()) != null) {
119
120         name = entry.getName()
121             .substring(entry.getName().lastIndexOf(File.separator) + 1, entry.getName().length());
122         if (expectedResultFileNameSet.contains(name)) {
123           expected = new String(expectedResultMap.get(name)).trim().replace("\r", "");
124           actual = new String(FileUtils.toByteArray(zis)).trim().replace("\r", "");
125           assertEquals("difference in file: " + name, expected, actual);
126
127           expectedResultFileNameSet.remove(name);
128         }
129       }
130       if (expectedResultFileNameSet.isEmpty()) {
131         expectedResultFileNameSet.forEach(System.out::println);
132       }
133     }
134     assertEquals(0, expectedResultFileNameSet.size());
135   }
136
137   private File translateZipFile(String basePath, HeatToToscaTranslator heatToToscaTranslator) throws IOException {
138     URL inputFilesUrl = this.getClass().getResource(basePath + IN_POSTFIX);
139     String path = inputFilesUrl.getPath();
140     TestUtils.addFilesToTranslator(heatToToscaTranslator, path);
141     TranslatorOutput translatorOutput = heatToToscaTranslator.translate();
142     Assert.assertNotNull(translatorOutput);
143     if (MapUtils.isNotEmpty(translatorOutput.getErrorMessages()) && MapUtils.isNotEmpty(
144         MessageContainerUtil
145             .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()))) {
146       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
147           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
148           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
149     }
150
151     File file = new File(path + "/VSP.zip");
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 }