Sorted out unit-test libraries in onboarding
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-impl / src / test / java / org / openecomp / sdc / validation / util / ValidationTestUtil.java
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.validation.util;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.net.URL;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Objects;
27 import org.apache.commons.collections4.MapUtils;
28 import org.apache.commons.io.IOUtils;
29 import org.junit.Assert;
30 import org.openecomp.core.utilities.file.FileUtils;
31 import org.openecomp.core.utilities.json.JsonUtil;
32 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
33 import org.openecomp.core.validation.types.GlobalValidationContext;
34 import org.openecomp.core.validation.types.MessageContainer;
35 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
36 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
37 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
38 import org.openecomp.sdc.heat.datatypes.model.Resource;
39 import org.openecomp.sdc.heat.services.HeatStructureUtil;
40 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
41 import org.openecomp.sdc.validation.ResourceValidator;
42 import org.openecomp.sdc.validation.ValidationContext;
43 import org.openecomp.sdc.validation.Validator;
44 import org.openecomp.sdc.validation.base.ResourceBaseValidator;
45
46 /**
47  * @author TALIO
48  * @since 26 Feb 2017
49  */
50 public class ValidationTestUtil {
51
52   private ValidationTestUtil(){}
53
54   public static GlobalValidationContext createGlobalContextFromPath(String path) {
55     GlobalValidationContext globalValidationContext = new GlobalValidationContext();
56     Map<String, byte[]> contentMap = getContentMapByPath(path);
57     if (contentMap == null) {
58       return null;
59     }
60     contentMap.forEach(globalValidationContext::addFileContext);
61
62     return globalValidationContext;
63   }
64
65   private static Map<String, byte[]> getContentMapByPath(String path) {
66     Map<String, byte[]> contentMap = new HashMap<>();
67     URL url = ValidationTestUtil.class.getResource(path);
68     File pathFile = new File(url.getFile());
69     File[] files;
70     if (pathFile.isDirectory()) {
71       files = pathFile.listFiles();
72     } else {
73       files = new File[]{pathFile};
74     }
75
76     if (files == null || files.length == 0) {
77       return null;
78     }
79
80     for (File file : files) {
81
82       try (FileInputStream fis = new FileInputStream(file)) {
83         contentMap.put(file.getName(), FileUtils.toByteArray(fis));
84       } catch (IOException e) {
85         throw new RuntimeException("Failed to read file: " + file, e);
86       }
87
88     }
89     return contentMap;
90   }
91
92   public static Map<String, MessageContainer> testValidator(Validator validator, String path) {
93
94     GlobalValidationContext globalValidationContext = createGlobalContextFromPath(path);
95     validator.validate(globalValidationContext);
96
97     assert globalValidationContext != null;
98     return globalValidationContext.getContextMessageContainers();
99
100
101   }
102
103   public static Map<String, MessageContainer> testValidator(ResourceBaseValidator baseValidator,
104           ResourceValidator resourceValidator,
105           String resourceTypeToValidate, String path) {
106
107     GlobalValidationContext globalContext = Objects.requireNonNull(
108             createGlobalContextFromPath(path), "Global validation context cannot be null");
109
110     ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext);
111     Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
112     Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent);
113
114     validateFiles(baseValidator, resourceValidator, globalContext, fileEnvMap, fileTypeMap,
115             resourceTypeToValidate);
116
117     return globalContext.getContextMessageContainers();
118   }
119
120   private static void validateFiles(ResourceBaseValidator baseValidator,
121           ResourceValidator resourceValidator,
122           GlobalValidationContext globalContext,
123           Map<String, FileData> fileEnvMap,
124           Map<String, FileData.Type> fileTypeMap,
125           String resourceTypeToValidate) {
126
127     Collection<String> files = globalContext.getFiles();
128     for(String fileName : files){
129       if(FileData.isHeatFile(fileTypeMap.get(fileName))) {
130         HeatOrchestrationTemplate heatOrchestrationTemplate =
131                 ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext);
132
133         if (Objects.isNull(heatOrchestrationTemplate)) {
134           continue;
135         }
136
137         ValidationContext validationContext = baseValidator.createValidationContext(fileName,
138                 fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(),
139                 heatOrchestrationTemplate, globalContext);
140
141         validateResources(fileName, resourceValidator, resourceTypeToValidate, validationContext,
142                 globalContext);
143       }
144     }
145   }
146
147   private static void validateResources(String fileName, ResourceValidator resourceValidator,
148           String resourceTypeToValidate, ValidationContext validationContext,
149           GlobalValidationContext globalValidationContext){
150
151     HeatOrchestrationTemplate heatOrchestrationTemplate =
152             ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalValidationContext);
153
154     Map<String, Resource> resourcesMap =
155             Objects.requireNonNull(heatOrchestrationTemplate, "Orchestration template cannot be null").getResources();
156
157     if(MapUtils.isEmpty(resourcesMap)){
158       return;
159     }
160
161     resourcesMap.entrySet()
162                 .stream()
163                 .filter(resourceEntry -> isResourceNeedToBeTested(resourceEntry.getValue().getType(), resourceTypeToValidate))
164                 .forEach(resourceEntry ->
165                                  resourceValidator.validate
166                                                            (fileName, resourceEntry, globalValidationContext, validationContext));
167   }
168
169   private static boolean isResourceNeedToBeTested(String currResource, String resourceToTest){
170     if(Objects.isNull(resourceToTest)){
171       return HeatStructureUtil.isNestedResource(currResource);
172     }
173
174     return currResource.equals(resourceToTest);
175   }
176
177   public static void validateErrorMessage(String actualMessage, String expected, String... params) {
178
179     Assert.assertEquals(actualMessage.replace("\n", "").replace("\r", ""),
180             ErrorMessagesFormatBuilder.getErrorWithParameters(expected, params).replace("\n", "")
181                                       .replace("\r", ""));
182   }
183
184   public static Map<String, Object> getResourceMap(String configFileName) throws IOException {
185     URL mockResource = ValidationTestUtil.class.getResource(configFileName);
186     String json = IOUtils.toString(mockResource.openStream(), "UTF-8");
187     return JsonUtil.json2Object(json, Map.class);
188   }
189 }