69367e962c918d65d8f69873d901954e40c090cb
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / utils / YamlTemplateParsingHandlerTest.java
1 /*-
2  * ============LICENSE_START===============================================
3  * ONAP SDC
4  * ========================================================================
5  * Modifications Copyright (c) 2019 Samsung
6  * ========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=================================================
19  */
20
21 package org.openecomp.sdc.be.components.impl.utils;
22
23 import mockit.Deencapsulation;
24 import org.apache.commons.collections.MapUtils;
25 import org.assertj.core.util.Lists;
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.BeforeClass;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.InjectMocks;
32 import org.mockito.Mock;
33 import org.mockito.junit.MockitoJUnitRunner;
34 import org.openecomp.sdc.be.components.csar.CsarInfo;
35 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
36 import org.openecomp.sdc.be.components.impl.AnnotationBusinessLogic;
37 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
38 import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
39 import org.openecomp.sdc.be.components.validation.AnnotationValidator;
40 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
41 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
42 import org.openecomp.sdc.be.model.CapabilityDefinition;
43 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
44 import org.openecomp.sdc.be.model.GroupProperty;
45 import org.openecomp.sdc.be.model.GroupTypeDefinition;
46 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
47 import org.openecomp.sdc.be.model.PolicyDefinition;
48 import org.openecomp.sdc.be.model.PolicyTypeDefinition;
49 import org.openecomp.sdc.be.model.Resource;
50 import org.openecomp.sdc.be.model.UploadArtifactInfo;
51 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
52 import org.openecomp.sdc.be.model.User;
53 import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
54 import org.openecomp.sdc.common.zip.ZipUtils;
55 import org.openecomp.sdc.common.zip.exception.ZipException;
56
57 import java.io.File;
58 import java.net.URISyntaxException;
59 import java.util.Collections;
60 import java.util.HashMap;
61 import java.util.List;
62 import java.util.Map;
63 import java.util.Optional;
64 import java.util.stream.Collectors;
65 import org.springframework.test.util.ReflectionTestUtils;
66
67 import static org.assertj.core.api.Assertions.assertThat;
68 import static org.junit.Assert.assertNotNull;
69 import static org.mockito.ArgumentMatchers.any;
70 import static org.mockito.ArgumentMatchers.eq;
71 import static org.mockito.Mockito.when;
72 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
73
74 @RunWith(MockitoJUnitRunner.class)
75 public class YamlTemplateParsingHandlerTest {
76
77     @Mock
78     private GroupTypeBusinessLogic groupTypeBusinessLogic;
79     @Mock
80     private AnnotationTypeOperations annotationTypeOperations;
81     @Mock
82     private AnnotationValidator annotationValidator;
83     @Mock
84     private JanusGraphDao janusGraphDao;
85     @Mock
86     private User user;
87     @Mock
88     private PolicyTypeBusinessLogic policyTypeBusinessLogic;
89
90     private YamlTemplateParsingHandler handler;
91
92     private static Map<String, byte[]> csar;
93     private static String resourceYml;
94
95     private final static String VFC_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup";
96     private final static String HEAT_GROUP_TYPE = "org.openecomp.groups.heat.HeatStack";
97     private final static String ROOT_GROUP_TYPE = "tosca.groups.Root";
98     private final static String OPENECOMP_ANTILOCATE_POLICY_TYPE = "org.openecomp.policies.placement.Antilocate";
99     private final static String ROOT_POLICIES_TYPE = "tosca.policies.Root";
100     private final static GroupTypeDefinition VfcInstanceGroupType = buildVfcInstanceGroupType();
101     private final static GroupTypeDefinition heatGroupType = buildHeatStackGroupType();
102     private final static GroupTypeDefinition rootGroupType = buildRootGroupType();
103     private static final PolicyTypeDefinition OPENECOMP_POLICY_TYPE = buildOpenecompPolicyType();
104     private final static String OPENECOMP_POLICY_NAME = "vepdg_server_group_policy";
105     private final static String CAPABILITY_TYPE = "org.openecomp.capabilities.VLANAssignment";
106     private final static String CAPABILITY_NAME = "vlan_assignment";
107     private static final String CSAR_FILE_PATH = "csars/with_groups.csar";
108     private static final String FILE_NAME = "MainServiceTemplate.yaml";
109     private static final String CSAR_UUID = "csarUUID";
110     private static final String RESOURCE_NAME = "resourceName";
111     private static final String MAIN_TEMPLATE_NAME = "Definitions/MainServiceTemplate.yaml";
112     private static final String NODE_NAME = "org.openecomp.resource.abstract.nodes.heat.mg";
113     private static final String MAIN_GROUP_NAME = "x_group";
114     private static final String NESTED_GROUP_NAME = "nested_mg_vepdg_group";
115
116     @InjectMocks
117     YamlTemplateParsingHandler testSubject;
118
119     @BeforeClass()
120     public static void prepareData() throws URISyntaxException, ZipException {
121         final File csarFile = new File(
122             YamlTemplateParsingHandlerTest.class.getClassLoader().getResource(CSAR_FILE_PATH).toURI());
123         csar = ZipUtils.readZip(csarFile, false);
124
125         Optional<String> keyOp = csar.keySet().stream().filter(k -> k.endsWith(FILE_NAME)).findAny();
126         byte[] mainTemplateService = keyOp.map(csar::get).orElse(null);
127         assertNotNull(mainTemplateService);
128
129         resourceYml = new String(mainTemplateService);
130     }
131
132     @Before
133     public void setup() {
134
135         AnnotationBusinessLogic annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations,
136                 annotationValidator);
137         handler = new YamlTemplateParsingHandler(janusGraphDao, groupTypeBusinessLogic, annotationBusinessLogic, policyTypeBusinessLogic);
138         ReflectionTestUtils.setField(handler, "policyTypeBusinessLogic", policyTypeBusinessLogic);
139         stubGetGroupType();
140         stubGetPolicyType();
141     }
142
143     @Test
144     public void parseResourceInfoFromOneNodeTest() {
145
146         String main_template_content = new String(csar.get(MAIN_TEMPLATE_NAME));
147         CsarInfo csarInfo = new CsarInfo(user, CSAR_UUID, csar, RESOURCE_NAME,
148                 MAIN_TEMPLATE_NAME, main_template_content, true);
149
150         Resource resource = new Resource();
151         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
152                 csarInfo.extractNodeTypesInfo(), NODE_NAME, resource);
153
154         validateParsedYaml(parsedYaml, NESTED_GROUP_NAME,
155                 Lists.newArrayList("heat_file", "description"));
156     }
157
158     @Test
159     public void parseResourceInfoFromYAMLTest() {
160
161         Resource resource = new Resource();
162         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
163                 new HashMap<>(), "", resource);
164         validateParsedYamlWithCapability(parsedYaml);
165     }
166
167     @Test
168     public void testSetArtifacts() {
169         UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
170         Map<String, Object> nodeTemplateJsonMap = new HashMap<>();
171         Map<String, String> nodeMap = new HashMap<>();
172         nodeMap.put("name","test_name");
173         nodeMap.put("type","test_type");
174         nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), nodeMap);
175         Deencapsulation.invoke(testSubject, "setArtifacts", nodeTemplateInfo, nodeTemplateJsonMap);
176         assertNotNull(nodeTemplateInfo.getArtifacts());
177     }
178
179     @Test
180     public void testCreateArtifactsModuleFromYaml() {
181         Map<String, Map<String, Map<String, String>>> nodeTemplateJsonMap = new HashMap<>();
182         Map<String, Map<String,String>> map0 = new HashMap<>();
183         Map<String, String> map1 = new HashMap<>();
184         map1.put("file", "test_file");
185         map1.put("type", "test_type");
186         map0.put("test_art", map1);
187         nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), map0);
188         Map<String, Map<String, UploadArtifactInfo>> result;
189         result = Deencapsulation.invoke(testSubject, "createArtifactsModuleFromYaml", nodeTemplateJsonMap);
190         Assert.assertTrue(MapUtils.isNotEmpty(result));
191         Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
192         Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
193         Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
194     }
195
196     @Test
197     public void testAddModuleNodeTemplateArtifacts() {
198         Map<String, Map<String, UploadArtifactInfo>> result = new HashMap<>();
199         Map<String, String> map1 = new HashMap<>();
200         map1.put("file", "test_file");
201         map1.put("type", "test_type");
202         Deencapsulation.invoke(testSubject, "addModuleNodeTemplateArtifacts", result, map1, "test_art");
203         Assert.assertTrue(MapUtils.isNotEmpty(result));
204         Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
205         Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
206         Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
207     }
208
209     @Test
210     public void testBuildModuleNodeTemplateArtifact() {
211         Map<String, String> map1 = new HashMap<>();
212         map1.put("file", "test_file");
213         map1.put("type", "test_type");
214         UploadArtifactInfo result;
215         result = Deencapsulation.invoke(testSubject, "buildModuleNodeTemplateArtifact", map1);
216         assertNotNull(result);
217         Assert.assertEquals("test_file", result.getFile());
218         Assert.assertEquals("test_type", result.getType());
219     }
220
221     @Test
222     public void testFillArtifact() {
223         Map<String, String> map1 = new HashMap<>();
224         map1.put("file", "test_file");
225         map1.put("type", "test_type");
226         UploadArtifactInfo result = new UploadArtifactInfo();
227         Deencapsulation.invoke(testSubject, "fillArtifact", result, map1);
228         assertNotNull(result);
229         Assert.assertEquals("test_file", result.getFile());
230         Assert.assertEquals("test_type", result.getType());
231     }
232
233     @Test
234     public void parseResourceWithPoliciesDefined() {
235         Resource resource = new Resource();
236         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
237                 new HashMap<>(), "", resource);
238         validateParsedYamlWithPolicies(parsedYaml);
239     }
240
241     private void validateParsedYaml(ParsedToscaYamlInfo parsedYaml, String group, List<String> expectedProp) {
242         assertThat(parsedYaml).isNotNull();
243         assertThat(parsedYaml.getGroups()).isNotNull().containsKey(group);
244         assertThat(parsedYaml.getGroups().get(group)).isNotNull();
245
246         assertThat(parsedYaml.getGroups().get(group).getProperties()).isNotNull();
247         assertThat(parsedYaml.getGroups().get(group).getProperties()
248                            .stream()
249                            .map(PropertyDataDefinition::getName)
250                            .collect(Collectors.toList()))
251                 .containsAll(expectedProp);
252
253         assertThat(parsedYaml.getGroups().get(group).getMembers()).isNotNull();
254     }
255
256     private void validateParsedYamlWithCapability(ParsedToscaYamlInfo parsedYaml) {
257
258         final List<String> expectedProp = Lists.newArrayList("vfc_parent_port_role",
259                 "network_collection_function", "vfc_instance_group_function", "subinterface_role");
260
261         validateParsedYaml(parsedYaml, MAIN_GROUP_NAME, expectedProp);
262
263         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()
264                            .get(CAPABILITY_TYPE)
265                            .get(0).getProperties().get(0).getValue()).isEqualTo("success");
266         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()).isNotNull();
267     }
268
269     private void stubGetGroupType() {
270         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE), any())).thenReturn(VfcInstanceGroupType);
271         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE), any())).thenReturn(heatGroupType);
272         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(ROOT_GROUP_TYPE), any())).thenReturn(rootGroupType);
273     }
274
275     private static GroupTypeDefinition buildRootGroupType() {
276         return createGroupTypeDefinition(ROOT_GROUP_TYPE, null,
277                 "The TOSCA Group Type all other TOSCA Group Types derive from");
278     }
279
280     private static GroupTypeDefinition buildHeatStackGroupType() {
281         GroupTypeDefinition groupType = createGroupTypeDefinition(HEAT_GROUP_TYPE, "tosca.groups.Root",
282                 "Grouped all heat resources which are in the same heat stack");
283
284         GroupProperty property1 = createGroupProperty("heat_file",
285                 "Heat file which associate to this group/heat stack", "SUPPORTED");
286
287         GroupProperty property2 = createGroupProperty("description",
288                 "Group description", "SUPPORTED");
289
290         groupType.setProperties(Lists.newArrayList(property1, property2));
291         return groupType;
292     }
293
294     private static GroupTypeDefinition buildVfcInstanceGroupType() {
295         GroupTypeDefinition groupType = createGroupTypeDefinition(VFC_GROUP_TYPE, "tosca.groups.Root",
296                 "Groups of VFCs with same parent port role");
297
298         GroupProperty property1 = createGroupProperty("vfc_instance_group_function",
299                 "Function of this VFC group", null);
300
301         GroupProperty property2 = createGroupProperty("vfc_parent_port_role",
302                 "Common role of parent ports of VFCs in this group", null);
303
304         GroupProperty property3 = createGroupProperty("network_collection_function",
305                 "Network collection function assigned to this group", null);
306
307         GroupProperty property4 = createGroupProperty("subinterface_role",
308                 "Common role of subinterfaces of VFCs in this group, criteria the group is created", null);
309
310         groupType.setProperties(Lists.newArrayList(property1, property2, property3, property4));
311
312         CapabilityDefinition capability = new CapabilityDefinition();
313         capability.setType(CAPABILITY_TYPE);
314         capability.setName(CAPABILITY_NAME);
315         ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty();
316         capabilityProperty.setName("vfc_instance_group_reference");
317         capabilityProperty.setType("string");
318         capability.setProperties(Collections.singletonList(capabilityProperty));
319
320         Map<String, CapabilityDefinition> capabilityMap = new HashMap<>();
321         capabilityMap.put(CAPABILITY_NAME, capability);
322         groupType.setCapabilities(capabilityMap);
323         return groupType;
324     }
325
326     private static GroupTypeDefinition createGroupTypeDefinition(String type, String derivedFrom, String description){
327         GroupTypeDefinition property = new GroupTypeDefinition();
328
329         if (type != null)
330             property.setType(type);
331
332         if (derivedFrom != null) {
333             property.setDerivedFrom(derivedFrom);
334         }
335
336         if (description != null) {
337             property.setDescription(description);
338         }
339
340         return property;
341     }
342     private static GroupProperty createGroupProperty(String name, String description,
343             String status){
344         GroupProperty property = new GroupProperty();
345         if (name != null)
346             property.setName(name);
347
348         if (description != null) {
349             property.setDescription(description);
350         }
351
352         if (status != null) {
353             property.setStatus(status);
354         }
355
356         property.setType("string");
357         property.setRequired(true);
358
359         return property;
360     }
361
362     private void validateParsedYamlWithPolicies(ParsedToscaYamlInfo parsedYaml) {
363         // validate  policies
364         assertThat(parsedYaml.getPolicies()).isNotNull();
365         assertThat(parsedYaml.getPolicies()).containsKey(OPENECOMP_POLICY_NAME);
366         assertThat(parsedYaml.getPolicies().get(OPENECOMP_POLICY_NAME)).isInstanceOf(PolicyDefinition.class);
367     }
368
369     private void stubGetPolicyType () {
370         when(policyTypeBusinessLogic.getLatestPolicyTypeByType(eq(OPENECOMP_ANTILOCATE_POLICY_TYPE), any())).thenReturn(
371                 OPENECOMP_POLICY_TYPE);
372     }
373
374     private static PolicyTypeDefinition buildOpenecompPolicyType() {
375         return createPolicyTypeDefinition(OPENECOMP_POLICY_NAME, OPENECOMP_ANTILOCATE_POLICY_TYPE, ROOT_POLICIES_TYPE,
376                 "The Openecomp Antilocate policy");
377     }
378
379     private static PolicyTypeDefinition createPolicyTypeDefinition(String policyName, String policyType, String derivedFrom, String description) {
380         PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition();
381         if (policyName != null && !policyName.isEmpty()) {
382             policyTypeDefinition.setName(policyName);
383         }
384         if (policyType != null) {
385             policyTypeDefinition.setType(policyType);
386         }
387         if (derivedFrom != null) {
388             policyTypeDefinition.setDerivedFrom(derivedFrom);
389         }
390         if (description != null) {
391             policyTypeDefinition.setDescription(description);
392         }
393         return policyTypeDefinition;
394     }
395 }