2387390df95b284754d111787f403e789edcb90f
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation;
18
19 import static org.junit.Assert.assertEquals;
20
21 import org.apache.commons.collections4.MapUtils;
22 import org.junit.Assert;
23 import org.junit.BeforeClass;
24 import org.junit.Rule;
25 import org.junit.rules.TestName;
26 import org.openecomp.core.translator.api.HeatToToscaTranslator;
27 import org.openecomp.core.translator.datatypes.TranslatorOutput;
28 import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
29 import org.openecomp.core.utilities.file.FileUtils;
30 import org.openecomp.core.validation.util.MessageContainerUtil;
31 import org.openecomp.sdc.common.errors.CoreException;
32 import org.openecomp.sdc.common.errors.ErrorCategory;
33 import org.openecomp.sdc.common.errors.ErrorCode;
34 import org.openecomp.sdc.common.togglz.ToggleableFeature;
35 import org.openecomp.sdc.datatypes.error.ErrorLevel;
36 import org.openecomp.sdc.datatypes.error.ErrorMessage;
37 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
38 import org.openecomp.sdc.translator.TestUtils;
39 import org.togglz.testing.TestFeatureManager;
40 import org.togglz.testing.TestFeatureManagerProvider;
41
42 import java.io.BufferedInputStream;
43 import java.io.File;
44 import java.io.FileInputStream;
45 import java.io.ByteArrayInputStream;
46 import java.io.IOException;
47 import java.net.URL;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Set;
53 import java.util.zip.ZipEntry;
54 import java.util.zip.ZipInputStream;
55
56
57 public class BaseFullTranslationTest {
58
59   public static final String IN_POSTFIX = "/in";
60   public static final String OUT_POSTFIX = "/out";
61
62   @Rule
63   public TestName name = new TestName();
64
65   protected static TestFeatureManager manager;
66   private static File tempDir = new File(System.getProperty("java.io.tmpdir"));
67
68   @BeforeClass
69   public static void enableToggleableFeatures(){
70     manager = new TestFeatureManager(ToggleableFeature.class);
71     manager.enableAll();
72     TestFeatureManagerProvider.setFeatureManager(manager);
73   }
74
75
76   public static void disableToggleableFeatures() {
77     manager.disableAll();
78     manager = null;
79     TestFeatureManagerProvider.setFeatureManager(null);
80   }
81
82   protected void testTranslationWithInit(String path) throws IOException {
83     byte[] translatedZipFile = initTranslatorAndTranslate(path);
84     testTranslation(path, translatedZipFile);
85   }
86
87   protected byte[] initTranslatorAndTranslate(String path) throws IOException {
88     HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
89     return translateZipFile(path, heatToToscaTranslator);
90   }
91
92   protected void testTranslation(String basePath, byte[] translatedZipFile) throws IOException {
93
94     URL url = BaseFullTranslationTest.class.getResource(basePath + OUT_POSTFIX);
95     Set<String> expectedResultFileNameSet = new HashSet<>();
96     Map<String, byte[]> expectedResultMap = new HashMap<>();
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 (ByteArrayInputStream fis = new ByteArrayInputStream(translatedZipFile);BufferedInputStream bis = new BufferedInputStream(fis);
110          ZipInputStream zis = new ZipInputStream(bis)) {
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 byte[] translateZipFile(String basePath, HeatToToscaTranslator heatToToscaTranslator) throws IOException {
136     URL inputFilesUrl = this.getClass().getResource(basePath + IN_POSTFIX);
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       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
145           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
146           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
147     }
148
149     byte[] data = new ToscaFileOutputServiceCsarImpl().createOutputFile(translatorOutput.getToscaServiceModel(), null);
150
151     return data;
152   }
153
154   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
155     StringBuilder sb = new StringBuilder();
156     errorMessages.entrySet().forEach(
157         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
158             .append(getErrorList(entry.getValue())));
159
160     return sb.toString();
161   }
162
163   private String getErrorList(List<ErrorMessage> errors) {
164     StringBuilder sb = new StringBuilder();
165     errors.forEach(
166         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
167             .append(System.lineSeparator()));
168     return sb.toString();
169   }
170
171 }