Upgrade Vulnerable Direct Dependencies [snakeyaml]
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-sdk / src / test / java / org / openecomp / sdc / validation / base / ResourceBaseValidatorTest.java
1 /*
2  * Copyright © 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 package org.openecomp.sdc.validation.base;
17
18 import static org.junit.jupiter.api.Assertions.assertEquals;
19 import static org.junit.jupiter.api.Assertions.assertTrue;
20
21 import org.apache.commons.collections4.MapUtils;
22 import org.apache.commons.io.IOUtils;
23 import org.junit.jupiter.api.Test;
24 import org.openecomp.core.utilities.file.FileUtils;
25 import org.openecomp.core.utilities.json.JsonUtil;
26 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
27 import org.openecomp.core.validation.types.GlobalValidationContext;
28 import org.openecomp.core.validation.types.MessageContainer;
29 import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration;
30 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
31 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
32 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
33 import org.openecomp.sdc.heat.datatypes.model.Resource;
34 import org.openecomp.sdc.heat.services.HeatStructureUtil;
35 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
36 import org.openecomp.sdc.validation.ResourceValidator;
37 import org.openecomp.sdc.validation.ValidationContext;
38 import org.openecomp.sdc.validation.Validator;
39 import org.openecomp.sdc.validation.type.ConfigConstants;
40 import org.openecomp.sdc.validation.util.ValidationUtil;
41
42 import java.io.File;
43 import java.io.FileInputStream;
44 import java.io.IOException;
45 import java.net.URL;
46 import java.util.*;
47
48 public class ResourceBaseValidatorTest {
49     private String testValidator = "testValidator";
50
51     @Test
52     public void testInvalidResourceType() {
53         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
54         Map<String, MessageContainer> messages = testValidator(resourceBaseValidator, "/InvalidResourceType");
55         assertEquals(messages.get("first.yaml").getErrorMessageList().get(0).getMessage(),
56                 "WARNING: [RBV1]: A resource has an invalid or unsupported type - null, Resource ID [FSB2]");
57     }
58
59     @Test
60     public void testInvalidHeatStructure() {
61         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
62         Map<String, MessageContainer> messages = testValidator(resourceBaseValidator, "/InvalidHeatStructure");
63         assertEquals(messages.get("first.yaml").getErrorMessageList().get(0).getMessage(),
64                 "ERROR: [RBV2]: Invalid HEAT format problem - [while scanning for the next " +
65                         "token\n" + "found character '\\t(TAB)' that cannot start any token. " +
66                         "(Do not use \\t(TAB) for indentation)\n" +
67                         " in 'reader', line 10, column 1:\n" +
68                         "    \t\t\tresources:\n" +
69                         "    ^\n" +
70                         "]");
71     }
72
73     @Test
74     public void testInitWithEmptyPropertiesMap() {
75         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
76         Map<String, Object> properties = new HashMap<>();
77         resourceBaseValidator.init(properties);
78         assertTrue(MapUtils.isEmpty(resourceBaseValidator.getResourceTypeToImpl()));
79     }
80
81     @Test
82     public void testInitPropertiesMap() {
83         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
84         initProperties(resourceBaseValidator, getValidImplementationConfiguration());
85
86         Map<String, ImplementationConfiguration> resourceTypeToImpl = resourceBaseValidator.getResourceTypeToImpl();
87         assertTrue(MapUtils.isNotEmpty(resourceTypeToImpl));
88         assertTrue(resourceTypeToImpl.containsKey(testValidator));
89     }
90
91     @Test
92     public void testInitPropertiesWithString() {
93         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
94         Map<String, Object> properties = new HashMap<>();
95         properties.put(testValidator, "invalidValue");
96         resourceBaseValidator.init(properties);
97         assertTrue(MapUtils.isEmpty(resourceBaseValidator.getResourceTypeToImpl()));
98     }
99
100     @Test
101     public void testInitPropertiesWithoutImplClass() {
102         ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
103         initProperties(resourceBaseValidator, new HashMap<>());
104         assertTrue(MapUtils.isEmpty(resourceBaseValidator.getResourceTypeToImpl()));
105     }
106
107     public Map<String, Object> getValidImplementationConfiguration() {
108         Map<String, Object> implConfiguration = new HashMap<>();
109         implConfiguration.put(ConfigConstants.Impl_Class, "org.openecomp.sdc.validation.impl.validators.ForbiddenResourceGuideLineValidator");
110         implConfiguration.put(ConfigConstants.Enable, true);
111
112         return implConfiguration;
113     }
114
115     private void initProperties(ResourceBaseValidator resourceBaseValidator, Map<String, Object> implementationConfiguration) {
116         Map<String, Object> properties = Collections.singletonMap(testValidator, implementationConfiguration);
117         resourceBaseValidator.init(properties);
118     }
119
120     public GlobalValidationContext createGlobalContextFromPath(String path) {
121         GlobalValidationContext globalValidationContext = new GlobalValidationContext();
122         Map<String, byte[]> contentMap = getContentMapByPath(path);
123         if (contentMap == null) {
124             return null;
125         }
126         contentMap.forEach(globalValidationContext::addFileContext);
127
128         return globalValidationContext;
129     }
130
131     private Map<String, byte[]> getContentMapByPath(String path) {
132         Map<String, byte[]> contentMap = new HashMap<>();
133         URL url = ResourceBaseValidator.class.getResource(path);
134         File pathFile = new File(url.getFile());
135         File[] files;
136         if (pathFile.isDirectory()) {
137             files = pathFile.listFiles();
138         } else {
139             files = new File[]{pathFile};
140         }
141
142         if (files == null || files.length == 0) {
143             return null;
144         }
145
146         for (File file : files) {
147
148             try (FileInputStream fis = new FileInputStream(file)) {
149                 contentMap.put(file.getName(), FileUtils.toByteArray(fis));
150             } catch (IOException e) {
151                 throw new RuntimeException("Failed to read file: " + file, e);
152             }
153
154         }
155         return contentMap;
156     }
157
158     public Map<String, MessageContainer> testValidator(Validator validator, String path) {
159         GlobalValidationContext globalValidationContext = createGlobalContextFromPath(path);
160         validator.validate(globalValidationContext);
161
162         assert globalValidationContext != null;
163         return globalValidationContext.getContextMessageContainers();
164     }
165
166     public Map<String, MessageContainer> testValidator(ResourceBaseValidator baseValidator,
167                                                        ResourceValidator resourceValidator,
168                                                        String resourceTypeToValidate, String path) {
169
170         GlobalValidationContext globalContext = Objects.requireNonNull(
171                 createGlobalContextFromPath(path), "Global validation context cannot be null");
172
173         ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext);
174         Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
175         Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent);
176
177         validateFiles(baseValidator, resourceValidator, globalContext, fileEnvMap, fileTypeMap,
178                 resourceTypeToValidate);
179
180         return globalContext.getContextMessageContainers();
181     }
182
183     private void validateFiles(ResourceBaseValidator baseValidator,
184                                ResourceValidator resourceValidator,
185                                GlobalValidationContext globalContext,
186                                Map<String, FileData> fileEnvMap,
187                                Map<String, FileData.Type> fileTypeMap,
188                                String resourceTypeToValidate) {
189
190         Collection<String> files = globalContext.getFiles();
191         for (String fileName : files) {
192             if (FileData.isHeatFile(fileTypeMap.get(fileName))) {
193                 HeatOrchestrationTemplate heatOrchestrationTemplate =
194                         ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext);
195
196                 if (Objects.isNull(heatOrchestrationTemplate)) {
197                     continue;
198                 }
199
200                 ValidationContext validationContext = baseValidator.createValidationContext(fileName,
201                         fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(),
202                         heatOrchestrationTemplate, globalContext);
203
204                 validateResources(fileName, resourceValidator, resourceTypeToValidate, validationContext,
205                         globalContext);
206             }
207         }
208     }
209
210     private void validateResources(String fileName, ResourceValidator resourceValidator,
211                                    String resourceTypeToValidate, ValidationContext validationContext,
212                                    GlobalValidationContext globalValidationContext) {
213
214         HeatOrchestrationTemplate heatOrchestrationTemplate =
215                 ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalValidationContext);
216
217         Map<String, Resource> resourcesMap =
218                 Objects.requireNonNull(heatOrchestrationTemplate, "Orchestration template cannot be null").getResources();
219
220         if (MapUtils.isEmpty(resourcesMap)) {
221             return;
222         }
223
224         resourcesMap.entrySet()
225                 .stream()
226                 .filter(resourceEntry -> isResourceNeedToBeTested(resourceEntry.getValue().getType(), resourceTypeToValidate))
227                 .forEach(resourceEntry ->
228                         resourceValidator.validate
229                                 (fileName, resourceEntry, globalValidationContext, validationContext));
230     }
231
232     private boolean isResourceNeedToBeTested(String currResource, String resourceToTest) {
233         if (Objects.isNull(resourceToTest)) {
234             return HeatStructureUtil.isNestedResource(currResource);
235         }
236
237         return currResource.equals(resourceToTest);
238     }
239
240     public void validateErrorMessage(String actualMessage, String expected, String... params) {
241         assertEquals(actualMessage.replace("\n", "").replace("\r", ""),
242                 ErrorMessagesFormatBuilder.getErrorWithParameters(expected, params).replace("\n", "")
243                         .replace("\r", ""));
244     }
245
246 }