ac64e0691751947ec11f3d8c91606fec672a16bb
[sdc.git] /
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.eq;
70 import static org.mockito.Mockito.when;
71 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
72
73 @RunWith(MockitoJUnitRunner.class)
74 public class YamlTemplateParsingHandlerTest {
75
76     @Mock
77     private GroupTypeBusinessLogic groupTypeBusinessLogic;
78     @Mock
79     private AnnotationTypeOperations annotationTypeOperations;
80     @Mock
81     private AnnotationValidator annotationValidator;
82     @Mock
83     private JanusGraphDao janusGraphDao;
84     @Mock
85     private User user;
86     @Mock
87     private PolicyTypeBusinessLogic policyTypeBusinessLogic;
88
89     private YamlTemplateParsingHandler handler;
90
91     private static Map<String, byte[]> csar;
92     private static String resourceYml;
93
94     private final static String VFC_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup";
95     private final static String HEAT_GROUP_TYPE = "org.openecomp.groups.heat.HeatStack";
96     private final static String ROOT_GROUP_TYPE = "tosca.groups.Root";
97     private final static String OPENECOMP_ANTILOCATE_POLICY_TYPE = "org.openecomp.policies.placement.Antilocate";
98     private final static String ROOT_POLICIES_TYPE = "tosca.policies.Root";
99     private final static GroupTypeDefinition VfcInstanceGroupType = buildVfcInstanceGroupType();
100     private final static GroupTypeDefinition heatGroupType = buildHeatStackGroupType();
101     private final static GroupTypeDefinition rootGroupType = buildRootGroupType();
102     private static final PolicyTypeDefinition OPENECOMP_POLICY_TYPE = buildOpenecompPolicyType();
103     private final static String OPENECOMP_POLICY_NAME = "vepdg_server_group_policy";
104     private final static String CAPABILITY_TYPE = "org.openecomp.capabilities.VLANAssignment";
105     private final static String CAPABILITY_NAME = "vlan_assignment";
106     private static final String CSAR_FILE_PATH = "csars/with_groups.csar";
107     private static final String FILE_NAME = "MainServiceTemplate.yaml";
108     private static final String CSAR_UUID = "csarUUID";
109     private static final String RESOURCE_NAME = "resourceName";
110     private static final String MAIN_TEMPLATE_NAME = "Definitions/MainServiceTemplate.yaml";
111     private static final String NODE_NAME = "org.openecomp.resource.abstract.nodes.heat.mg";
112     private static final String MAIN_GROUP_NAME = "x_group";
113     private static final String NESTED_GROUP_NAME = "nested_mg_vepdg_group";
114
115     @InjectMocks
116     YamlTemplateParsingHandler testSubject;
117
118     @BeforeClass()
119     public static void prepareData() throws URISyntaxException, ZipException {
120         final File csarFile = new File(
121             YamlTemplateParsingHandlerTest.class.getClassLoader().getResource(CSAR_FILE_PATH).toURI());
122         csar = ZipUtils.readZip(csarFile, false);
123
124         Optional<String> keyOp = csar.keySet().stream().filter(k -> k.endsWith(FILE_NAME)).findAny();
125         byte[] mainTemplateService = keyOp.map(csar::get).orElse(null);
126         assertNotNull(mainTemplateService);
127
128         resourceYml = new String(mainTemplateService);
129     }
130
131     @Before
132     public void setup() {
133
134         AnnotationBusinessLogic annotationBusinessLogic = new AnnotationBusinessLogic(annotationTypeOperations,
135                 annotationValidator);
136         handler = new YamlTemplateParsingHandler(janusGraphDao, groupTypeBusinessLogic, annotationBusinessLogic, policyTypeBusinessLogic);
137         ReflectionTestUtils.setField(handler, "policyTypeBusinessLogic", policyTypeBusinessLogic);
138         stubGetGroupType();
139         stubGetPolicyType();
140     }
141
142     @Test
143     public void parseResourceInfoFromOneNodeTest() {
144
145         String main_template_content = new String(csar.get(MAIN_TEMPLATE_NAME));
146         CsarInfo csarInfo = new CsarInfo(user, CSAR_UUID, csar, RESOURCE_NAME,
147                 MAIN_TEMPLATE_NAME, main_template_content, true);
148
149         Resource resource = new Resource();
150         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
151                 csarInfo.extractNodeTypesInfo(), NODE_NAME, resource);
152
153         validateParsedYaml(parsedYaml, NESTED_GROUP_NAME,
154                 Lists.newArrayList("heat_file", "description"));
155     }
156
157     @Test
158     public void parseResourceInfoFromYAMLTest() {
159
160         Resource resource = new Resource();
161         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
162                 new HashMap<>(), "", resource);
163         validateParsedYamlWithCapability(parsedYaml);
164     }
165
166     @Test
167     public void testSetArtifacts() {
168         UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
169         Map<String, Object> nodeTemplateJsonMap = new HashMap<>();
170         Map<String, String> nodeMap = new HashMap<>();
171         nodeMap.put("name","test_name");
172         nodeMap.put("type","test_type");
173         nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), nodeMap);
174         Deencapsulation.invoke(testSubject, "setArtifacts", nodeTemplateInfo, nodeTemplateJsonMap);
175         assertNotNull(nodeTemplateInfo.getArtifacts());
176     }
177
178     @Test
179     public void testCreateArtifactsModuleFromYaml() {
180         Map<String, Map<String, Map<String, String>>> nodeTemplateJsonMap = new HashMap<>();
181         Map<String, Map<String,String>> map0 = new HashMap<>();
182         Map<String, String> map1 = new HashMap<>();
183         map1.put("file", "test_file");
184         map1.put("type", "test_type");
185         map0.put("test_art", map1);
186         nodeTemplateJsonMap.put(ARTIFACTS.getElementName(), map0);
187         Map<String, Map<String, UploadArtifactInfo>> result;
188         result = Deencapsulation.invoke(testSubject, "createArtifactsModuleFromYaml", nodeTemplateJsonMap);
189         Assert.assertTrue(MapUtils.isNotEmpty(result));
190         Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
191         Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
192         Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
193     }
194
195     @Test
196     public void testAddModuleNodeTemplateArtifacts() {
197         Map<String, Map<String, UploadArtifactInfo>> result = new HashMap<>();
198         Map<String, String> map1 = new HashMap<>();
199         map1.put("file", "test_file");
200         map1.put("type", "test_type");
201         Deencapsulation.invoke(testSubject, "addModuleNodeTemplateArtifacts", result, map1, "test_art");
202         Assert.assertTrue(MapUtils.isNotEmpty(result));
203         Assert.assertTrue(MapUtils.isNotEmpty(result.get(ARTIFACTS.getElementName())));
204         Assert.assertEquals("test_file", result.get(ARTIFACTS.getElementName()).get("test_art").getFile());
205         Assert.assertEquals("test_type", result.get(ARTIFACTS.getElementName()).get("test_art").getType());
206     }
207
208     @Test
209     public void testBuildModuleNodeTemplateArtifact() {
210         Map<String, String> map1 = new HashMap<>();
211         map1.put("file", "test_file");
212         map1.put("type", "test_type");
213         UploadArtifactInfo result;
214         result = Deencapsulation.invoke(testSubject, "buildModuleNodeTemplateArtifact", map1);
215         assertNotNull(result);
216         Assert.assertEquals("test_file", result.getFile());
217         Assert.assertEquals("test_type", result.getType());
218     }
219
220     @Test
221     public void testFillArtifact() {
222         Map<String, String> map1 = new HashMap<>();
223         map1.put("file", "test_file");
224         map1.put("type", "test_type");
225         UploadArtifactInfo result = new UploadArtifactInfo();
226         Deencapsulation.invoke(testSubject, "fillArtifact", result, map1);
227         assertNotNull(result);
228         Assert.assertEquals("test_file", result.getFile());
229         Assert.assertEquals("test_type", result.getType());
230     }
231
232     @Test
233     public void parseResourceWithPoliciesDefined() {
234         Resource resource = new Resource();
235         ParsedToscaYamlInfo parsedYaml = handler.parseResourceInfoFromYAML(FILE_NAME, resourceYml, new HashMap<>(),
236                 new HashMap<>(), "", resource);
237         validateParsedYamlWithPolicies(parsedYaml);
238     }
239
240     private void validateParsedYaml(ParsedToscaYamlInfo parsedYaml, String group, List<String> expectedProp) {
241         assertThat(parsedYaml).isNotNull();
242         assertThat(parsedYaml.getGroups()).isNotNull().containsKey(group);
243         assertThat(parsedYaml.getGroups().get(group)).isNotNull();
244
245         assertThat(parsedYaml.getGroups().get(group).getProperties()).isNotNull();
246         assertThat(parsedYaml.getGroups().get(group).getProperties()
247                            .stream()
248                            .map(PropertyDataDefinition::getName)
249                            .collect(Collectors.toList()))
250                 .containsAll(expectedProp);
251
252         assertThat(parsedYaml.getGroups().get(group).getMembers()).isNotNull();
253     }
254
255     private void validateParsedYamlWithCapability(ParsedToscaYamlInfo parsedYaml) {
256
257         final List<String> expectedProp = Lists.newArrayList("vfc_parent_port_role",
258                 "network_collection_function", "vfc_instance_group_function", "subinterface_role");
259
260         validateParsedYaml(parsedYaml, MAIN_GROUP_NAME, expectedProp);
261
262         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()
263                            .get(CAPABILITY_TYPE)
264                            .get(0).getProperties().get(0).getValue()).isEqualTo("success");
265         assertThat(parsedYaml.getGroups().get(MAIN_GROUP_NAME).getCapabilities()).isNotNull();
266     }
267
268     private void stubGetGroupType() {
269         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(VFC_GROUP_TYPE))).thenReturn(VfcInstanceGroupType);
270         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(HEAT_GROUP_TYPE))).thenReturn(heatGroupType);
271         when(groupTypeBusinessLogic.getLatestGroupTypeByType(eq(ROOT_GROUP_TYPE))).thenReturn(rootGroupType);
272     }
273
274     private static GroupTypeDefinition buildRootGroupType() {
275         return createGroupTypeDefinition(ROOT_GROUP_TYPE, null,
276                 "The TOSCA Group Type all other TOSCA Group Types derive from");
277     }
278
279     private static GroupTypeDefinition buildHeatStackGroupType() {
280         GroupTypeDefinition groupType = createGroupTypeDefinition(HEAT_GROUP_TYPE, "tosca.groups.Root",
281                 "Grouped all heat resources which are in the same heat stack");
282
283         GroupProperty property1 = createGroupProperty("heat_file",
284                 "Heat file which associate to this group/heat stack", "SUPPORTED");
285
286         GroupProperty property2 = createGroupProperty("description",
287                 "Group description", "SUPPORTED");
288
289         groupType.setProperties(Lists.newArrayList(property1, property2));
290         return groupType;
291     }
292
293     private static GroupTypeDefinition buildVfcInstanceGroupType() {
294         GroupTypeDefinition groupType = createGroupTypeDefinition(VFC_GROUP_TYPE, "tosca.groups.Root",
295                 "Groups of VFCs with same parent port role");
296
297         GroupProperty property1 = createGroupProperty("vfc_instance_group_function",
298                 "Function of this VFC group", null);
299
300         GroupProperty property2 = createGroupProperty("vfc_parent_port_role",
301                 "Common role of parent ports of VFCs in this group", null);
302
303         GroupProperty property3 = createGroupProperty("network_collection_function",
304                 "Network collection function assigned to this group", null);
305
306         GroupProperty property4 = createGroupProperty("subinterface_role",
307                 "Common role of subinterfaces of VFCs in this group, criteria the group is created", null);
308
309         groupType.setProperties(Lists.newArrayList(property1, property2, property3, property4));
310
311         CapabilityDefinition capability = new CapabilityDefinition();
312         capability.setType(CAPABILITY_TYPE);
313         capability.setName(CAPABILITY_NAME);
314         ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty();
315         capabilityProperty.setName("vfc_instance_group_reference");
316         capabilityProperty.setType("string");
317         capability.setProperties(Collections.singletonList(capabilityProperty));
318
319         Map<String, CapabilityDefinition> capabilityMap = new HashMap<>();
320         capabilityMap.put(CAPABILITY_NAME, capability);
321         groupType.setCapabilities(capabilityMap);
322         return groupType;
323     }
324
325     private static GroupTypeDefinition createGroupTypeDefinition(String type, String derivedFrom, String description){
326         GroupTypeDefinition property = new GroupTypeDefinition();
327
328         if (type != null)
329             property.setType(type);
330
331         if (derivedFrom != null) {
332             property.setDerivedFrom(derivedFrom);
333         }
334
335         if (description != null) {
336             property.setDescription(description);
337         }
338
339         return property;
340     }
341     private static GroupProperty createGroupProperty(String name, String description,
342             String status){
343         GroupProperty property = new GroupProperty();
344         if (name != null)
345             property.setName(name);
346
347         if (description != null) {
348             property.setDescription(description);
349         }
350
351         if (status != null) {
352             property.setStatus(status);
353         }
354
355         property.setType("string");
356         property.setRequired(true);
357
358         return property;
359     }
360
361     private void validateParsedYamlWithPolicies(ParsedToscaYamlInfo parsedYaml) {
362         // validate  policies
363         assertThat(parsedYaml.getPolicies()).isNotNull();
364         assertThat(parsedYaml.getPolicies()).containsKey(OPENECOMP_POLICY_NAME);
365         assertThat(parsedYaml.getPolicies().get(OPENECOMP_POLICY_NAME)).isInstanceOf(PolicyDefinition.class);
366     }
367
368     private void stubGetPolicyType () {
369         when(policyTypeBusinessLogic.getLatestPolicyTypeByType(eq(OPENECOMP_ANTILOCATE_POLICY_TYPE))).thenReturn(
370                 OPENECOMP_POLICY_TYPE);
371     }
372
373     private static PolicyTypeDefinition buildOpenecompPolicyType() {
374         return createPolicyTypeDefinition(OPENECOMP_POLICY_NAME, OPENECOMP_ANTILOCATE_POLICY_TYPE, ROOT_POLICIES_TYPE,
375                 "The Openecomp Antilocate policy");
376     }
377
378     private static PolicyTypeDefinition createPolicyTypeDefinition(String policyName, String policyType, String derivedFrom, String description) {
379         PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition();
380         if (policyName != null && !policyName.isEmpty()) {
381             policyTypeDefinition.setName(policyName);
382         }
383         if (policyType != null) {
384             policyTypeDefinition.setType(policyType);
385         }
386         if (derivedFrom != null) {
387             policyTypeDefinition.setDerivedFrom(derivedFrom);
388         }
389         if (description != null) {
390             policyTypeDefinition.setDescription(description);
391         }
392         return policyTypeDefinition;
393     }
394 }