Plugin to Generate Service ETSI NSD CSAR
[sdc.git] / catalog-be-plugins / etsi-nfv-nsd-csar-plugin / src / test / java / org / openecomp / sdc / be / plugins / etsi / nfv / nsd / generator / NsDescriptorGeneratorImplTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        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.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.sdc.be.plugins.etsi.nfv.nsd.generator;
21
22 import static org.hamcrest.MatcherAssert.assertThat;
23 import static org.hamcrest.Matchers.anEmptyMap;
24 import static org.hamcrest.Matchers.greaterThan;
25 import static org.hamcrest.Matchers.not;
26 import static org.hamcrest.core.Is.is;
27 import static org.hamcrest.core.IsNull.notNullValue;
28 import static org.hamcrest.core.IsNull.nullValue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.anyBoolean;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import com.google.common.collect.ImmutableList;
35 import com.google.common.collect.ImmutableMap;
36 import fj.data.Either;
37 import java.io.ByteArrayInputStream;
38 import java.io.IOException;
39 import java.util.ArrayList;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43 import org.junit.jupiter.api.BeforeEach;
44 import org.junit.jupiter.api.Test;
45 import org.mockito.Mock;
46 import org.mockito.MockitoAnnotations;
47 import org.openecomp.sdc.be.config.Configuration;
48 import org.openecomp.sdc.be.config.ConfigurationManager;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.model.Component;
51 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.exception.NsdException;
52 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.model.Nsd;
53 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.model.VnfDescriptor;
54 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.tosca.yaml.ToscaTemplateYamlGenerator;
55 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
56 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
57 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
58 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
59 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
60 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraint;
61 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintValidValues;
62 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
63 import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability;
64 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
65 import org.openecomp.sdc.common.api.ConfigurationSource;
66 import org.springframework.beans.BeansException;
67 import org.springframework.beans.factory.ObjectProvider;
68 import org.yaml.snakeyaml.Yaml;
69
70 class NsDescriptorGeneratorImplTest {
71
72     private static final String VNFD_AMF_NODE_NAME = "vnfd_amf";
73     private static final String VIRTUAL_LINK_REQUIREMENT_NAME = "virtual_link";
74
75     @Mock
76     private ToscaExportHandler toscaExportHandler;
77
78     private final ObjectProvider<ToscaTemplateYamlGenerator> toscaTemplateYamlGeneratorProvider = new ObjectProvider<ToscaTemplateYamlGenerator>() {
79         @Override
80         public ToscaTemplateYamlGenerator getObject(Object... args) {
81             return new ToscaTemplateYamlGenerator((ToscaTemplate) args[0]);
82         }
83
84         @Override
85         public ToscaTemplateYamlGenerator getIfAvailable() {
86             return null;
87         }
88
89         @Override
90         public ToscaTemplateYamlGenerator getIfUnique() {
91             return null;
92         }
93
94         @Override
95         public ToscaTemplateYamlGenerator getObject() {
96             return null;
97         }
98     };
99
100     private NsDescriptorGeneratorImpl nsDescriptorGenerator;
101
102     @BeforeEach
103     void setUp() {
104         setUpConfigurationMock();
105         MockitoAnnotations.initMocks(this);
106         nsDescriptorGenerator = new NsDescriptorGeneratorImpl(toscaExportHandler, toscaTemplateYamlGeneratorProvider);
107     }
108
109     private void setUpConfigurationMock() {
110         final List<Map<String, Map<String, String>>> defaultImports = new ArrayList<>();
111         final Map<String, Map<String, String>> importMap = new HashMap<>();
112         final Map<String, String> nodeImportEntry = new HashMap<>();
113         nodeImportEntry.put("file", "nodes.yml");
114         importMap.put("nodes", nodeImportEntry);
115         defaultImports.add(importMap);
116
117         final ConfigurationSource configurationSource = mock(ConfigurationSource.class);
118         final Configuration configuration = new Configuration();
119         configuration.setDefaultImports(defaultImports);
120         configuration.setHeatEnvArtifactHeader("");
121         configuration.setHeatEnvArtifactFooter("");
122         when(configurationSource.getAndWatchConfiguration(any(), any())).thenReturn(configuration);
123         new ConfigurationManager(configurationSource);
124     }
125
126     @Test
127     void testGenerate() throws IOException, NsdException {
128         //given
129         final Component component = mock(Component.class);
130         when(component.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE);
131         final ToscaTemplate componentToscaTemplate = new ToscaTemplate("");
132         final ToscaTopolgyTemplate componentToscaTopologyTemplate = new ToscaTopolgyTemplate();
133         componentToscaTemplate.setTopology_template(componentToscaTopologyTemplate);
134
135         final HashMap<String, ToscaNodeTemplate> nodeTemplateMap = new HashMap<>();
136         final ToscaNodeTemplate vnfAmfNodeTemplate = new ToscaNodeTemplate();
137         vnfAmfNodeTemplate.setType("com.ericsson.resource.abstract.Ericsson.AMF");
138         //a property to be excluded
139         vnfAmfNodeTemplate.setProperties(ImmutableMap.of("nf_naming_code", new ToscaProperty()));
140         //a property that wont be excluded
141         vnfAmfNodeTemplate.setProperties(ImmutableMap.of("will_not_be_excluded", new ToscaProperty()));
142         nodeTemplateMap.put(VNFD_AMF_NODE_NAME, vnfAmfNodeTemplate);
143         
144         final Map<String, ToscaTemplateCapability> vnfAmfCapabilities = new HashMap<>();
145         vnfAmfCapabilities.put("myCapability", new ToscaTemplateCapability());
146                 vnfAmfNodeTemplate.setCapabilities(vnfAmfCapabilities);
147         componentToscaTopologyTemplate.setNode_templates(nodeTemplateMap);
148         
149         final SubstitutionMapping substitutionMapping = mock(SubstitutionMapping.class);
150         Map<String, String[]> requirements = new HashMap<>();
151         String[] requirementAssignment = {"VNF1", VIRTUAL_LINK_REQUIREMENT_NAME};
152         requirements.put(VIRTUAL_LINK_REQUIREMENT_NAME, requirementAssignment);
153                 when(substitutionMapping.getRequirements()).thenReturn(requirements);
154                 Map<String, String[]> capabilities = new HashMap<>();
155         String[] capabilitiesAssignment = {"VNF1", "capability1"};
156         capabilities.put("capability", capabilitiesAssignment);
157                 when(substitutionMapping.getCapabilities()).thenReturn(capabilities);
158                 componentToscaTopologyTemplate.setSubstitution_mappings(substitutionMapping);
159
160         final ToscaTemplate componentInterfaceToscaTemplate = new ToscaTemplate("");
161         final ToscaNodeType interfaceToscaNodeType = new ToscaNodeType();
162         interfaceToscaNodeType.setProperties(
163             ImmutableMap.of("designer", createToscaProperty("designerValue"),
164                 "version", createToscaProperty("versionValue"),
165                 "name", createToscaProperty("nameValue"),
166                 "invariant_id", createToscaProperty("invariantIdValue"))
167         );
168         final String nsNodeTypeName = "nsNodeTypeName";
169         componentInterfaceToscaTemplate.setNode_types(ImmutableMap.of(nsNodeTypeName, interfaceToscaNodeType));
170
171
172         when(toscaExportHandler.convertToToscaTemplate(component)).thenReturn(Either.left(componentToscaTemplate));
173         when(toscaExportHandler.convertInterfaceNodeType(any(), any(), any(), any(), anyBoolean()))
174             .thenReturn(Either.left(componentInterfaceToscaTemplate));
175
176         final List<VnfDescriptor> vnfDescriptorList = new ArrayList<>();
177         VnfDescriptor vnfDescriptor1 = new VnfDescriptor();
178         vnfDescriptor1.setName(VNFD_AMF_NODE_NAME);
179         vnfDescriptor1.setVnfdFileName("vnfd_amf.yaml");
180         vnfDescriptor1.setNodeType("com.ericsson.resource.abstract.Ericsson.AMF");
181
182         vnfDescriptorList.add(vnfDescriptor1);
183
184         //when
185         final Nsd nsd = nsDescriptorGenerator.generate(component, vnfDescriptorList).orElse(null);
186         //then
187         assertThat("Nsd should not be null", nsd, is(notNullValue()));
188         assertThat("Nsd designer should be as expected", nsd.getDesigner(), is("designerValue"));
189         assertThat("Nsd version should be as expected", nsd.getVersion(), is("versionValue"));
190         assertThat("Nsd name should be as expected", nsd.getName(), is("nameValue"));
191         assertThat("Nsd invariantId should be as expected", nsd.getInvariantId(), is("invariantIdValue"));
192         assertThat("Nsd content should not be empty", nsd.getContents(), is(notNullValue()));
193         assertThat("Nsd content should not be empty", nsd.getContents().length, is(greaterThan(0)));
194
195         final Map<String, Object> toscaTemplateYaml = readYamlAsMap(nsd.getContents());
196         @SuppressWarnings("unchecked")
197         final Map<String, Object> topologyTemplate = (Map<String, Object>) toscaTemplateYaml.get("topology_template");
198         assertThat("topology_template should not be empty", topologyTemplate, is(not(anEmptyMap())));
199         @SuppressWarnings("unchecked")
200         final Map<String, Object> substitutionMappings =
201             (Map<String, Object>) topologyTemplate.get("substitution_mappings");
202         assertThat("substitution_mappings should not be empty", substitutionMappings, is(not(anEmptyMap())));
203         assertThat("substitution_mappings->node_type should not be null",
204             substitutionMappings.get("node_type"), is(notNullValue()));
205         assertThat("substitution_mappings->node_type should be as expected",
206             substitutionMappings.get("node_type"), is(nsNodeTypeName));
207         
208         final Map<String, List<String>> subMappingRequirements = (Map<String, List<String>>) substitutionMappings.get("requirements");
209         assertThat(subMappingRequirements.get(VIRTUAL_LINK_REQUIREMENT_NAME).get(0), is("VNF1"));
210         assertThat(subMappingRequirements.get(VIRTUAL_LINK_REQUIREMENT_NAME).get(1), is(VIRTUAL_LINK_REQUIREMENT_NAME));
211         final Map<String, List<String>> subMappingCapabilities = (Map<String, List<String>>) substitutionMappings.get("capabilities");
212         assertThat(subMappingCapabilities.get("capability").get(0), is("VNF1"));
213         assertThat(subMappingCapabilities.get("capability").get(1), is("capability1"));
214         
215         @SuppressWarnings("unchecked")
216                 final Map<String, Object> nodeTemplates =
217                 (Map<String, Object>) topologyTemplate.get("node_templates");
218         @SuppressWarnings("unchecked")
219                 final Map<String, Object> nodeTemplate =
220                 (Map<String, Object>) nodeTemplates.get(VNFD_AMF_NODE_NAME);
221         assertThat("capabilities should be null",
222                         nodeTemplate.get("capabilities"), is(nullValue()));
223     }
224
225     private ToscaProperty createToscaProperty(final String value) {
226         final ToscaProperty toscaProperty = new ToscaProperty();
227         final ToscaPropertyConstraint toscaPropertyConstraint =
228             new ToscaPropertyConstraintValidValues(ImmutableList.of(value));
229         toscaProperty.setConstraints(ImmutableList.of(toscaPropertyConstraint));
230         return toscaProperty;
231     }
232
233     @SuppressWarnings("unchecked")
234     private Map<String, Object> readYamlAsMap(final byte[] yamlContents) throws IOException {
235         final Yaml yaml = new Yaml();
236         try (final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(yamlContents)) {
237             return  (Map<String, Object>) yaml.load(byteArrayInputStream);
238         }
239     }
240 }