2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.openecomp.sdc.validation.base;
18 import static org.junit.jupiter.api.Assertions.assertEquals;
19 import static org.junit.jupiter.api.Assertions.assertTrue;
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;
43 import java.io.FileInputStream;
44 import java.io.IOException;
48 public class ResourceBaseValidatorTest {
49 private String testValidator = "testValidator";
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]");
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" +
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()));
82 public void testInitPropertiesMap() {
83 ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
84 initProperties(resourceBaseValidator, getValidImplementationConfiguration());
86 Map<String, ImplementationConfiguration> resourceTypeToImpl = resourceBaseValidator.getResourceTypeToImpl();
87 assertTrue(MapUtils.isNotEmpty(resourceTypeToImpl));
88 assertTrue(resourceTypeToImpl.containsKey(testValidator));
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()));
101 public void testInitPropertiesWithoutImplClass() {
102 ResourceBaseValidator resourceBaseValidator = new ResourceBaseValidator();
103 initProperties(resourceBaseValidator, new HashMap<>());
104 assertTrue(MapUtils.isEmpty(resourceBaseValidator.getResourceTypeToImpl()));
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);
112 return implConfiguration;
115 private void initProperties(ResourceBaseValidator resourceBaseValidator, Map<String, Object> implementationConfiguration) {
116 Map<String, Object> properties = Collections.singletonMap(testValidator, implementationConfiguration);
117 resourceBaseValidator.init(properties);
120 public GlobalValidationContext createGlobalContextFromPath(String path) {
121 GlobalValidationContext globalValidationContext = new GlobalValidationContext();
122 Map<String, byte[]> contentMap = getContentMapByPath(path);
123 if (contentMap == null) {
126 contentMap.forEach(globalValidationContext::addFileContext);
128 return globalValidationContext;
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());
136 if (pathFile.isDirectory()) {
137 files = pathFile.listFiles();
139 files = new File[]{pathFile};
142 if (files == null || files.length == 0) {
146 for (File file : files) {
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);
158 public Map<String, MessageContainer> testValidator(Validator validator, String path) {
159 GlobalValidationContext globalValidationContext = createGlobalContextFromPath(path);
160 validator.validate(globalValidationContext);
162 assert globalValidationContext != null;
163 return globalValidationContext.getContextMessageContainers();
166 public Map<String, MessageContainer> testValidator(ResourceBaseValidator baseValidator,
167 ResourceValidator resourceValidator,
168 String resourceTypeToValidate, String path) {
170 GlobalValidationContext globalContext = Objects.requireNonNull(
171 createGlobalContextFromPath(path), "Global validation context cannot be null");
173 ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext);
174 Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
175 Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent);
177 validateFiles(baseValidator, resourceValidator, globalContext, fileEnvMap, fileTypeMap,
178 resourceTypeToValidate);
180 return globalContext.getContextMessageContainers();
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) {
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);
196 if (Objects.isNull(heatOrchestrationTemplate)) {
200 ValidationContext validationContext = baseValidator.createValidationContext(fileName,
201 fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(),
202 heatOrchestrationTemplate, globalContext);
204 validateResources(fileName, resourceValidator, resourceTypeToValidate, validationContext,
210 private void validateResources(String fileName, ResourceValidator resourceValidator,
211 String resourceTypeToValidate, ValidationContext validationContext,
212 GlobalValidationContext globalValidationContext) {
214 HeatOrchestrationTemplate heatOrchestrationTemplate =
215 ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalValidationContext);
217 Map<String, Resource> resourcesMap =
218 Objects.requireNonNull(heatOrchestrationTemplate, "Orchestration template cannot be null").getResources();
220 if (MapUtils.isEmpty(resourcesMap)) {
224 resourcesMap.entrySet()
226 .filter(resourceEntry -> isResourceNeedToBeTested(resourceEntry.getValue().getType(), resourceTypeToValidate))
227 .forEach(resourceEntry ->
228 resourceValidator.validate
229 (fileName, resourceEntry, globalValidationContext, validationContext));
232 private boolean isResourceNeedToBeTested(String currResource, String resourceToTest) {
233 if (Objects.isNull(resourceToTest)) {
234 return HeatStructureUtil.isNestedResource(currResource);
237 return currResource.equals(resourceToTest);
240 public void validateErrorMessage(String actualMessage, String expected, String... params) {
241 assertEquals(actualMessage.replace("\n", "").replace("\r", ""),
242 ErrorMessagesFormatBuilder.getErrorWithParameters(expected, params).replace("\n", "")