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