aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/impl/ToscaConverterImplTest.java
blob: 3e4e62a0d1477f91993c767cd2022d53fed06ed8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Nordix Foundation
 *  ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  SPDX-License-Identifier: Apache-2.0
 *  ============LICENSE_END=========================================================
 */

package org.openecomp.core.impl;

import org.apache.commons.collections.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
import org.onap.sdc.tosca.datatypes.model.*;
import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
import org.onap.sdc.tosca.services.YamlUtil;
import org.openecomp.core.converter.ToscaConverter;
import org.openecomp.core.utilities.file.FileContentHandler;
import org.openecomp.core.utilities.file.FileUtils;
import org.openecomp.core.utilities.json.JsonUtil;
import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.NotDirectoryException;
import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.openecomp.core.converter.datatypes.Constants.globalStName;
import static org.openecomp.core.converter.datatypes.Constants.mainStName;

public class ToscaConverterImplTest {

  private static final ToscaConverter toscaConverter = new ToscaConverterImpl();
  private static final String VIRTUAL_LINK = "virtualLink";
  private static final String UNBOUNDED = "UNBOUNDED";
  private static final String BASE_DIR = "/mock/toscaConverter";


  @Test
  public void testConvertMainSt() throws IOException {
    String inputFilesPath = BASE_DIR + "/convertMainSt/in";
    String outputFilesPath = BASE_DIR + "/convertMainSt/out";

    convertAndValidate(inputFilesPath, outputFilesPath);
  }

  @Test
  public void testNodesConversion() throws IOException {
    String inputFilesPath = BASE_DIR + "/convertCsar/in";
    String outputFilesPath = BASE_DIR + "/convertCsar/out";

    convertAndValidate(inputFilesPath, outputFilesPath);
  }

  @Test
  public void testParameterConversion() throws IOException {
    String inputFilesPath = BASE_DIR + "/convertParameters/in";
    String outputFilesPath = BASE_DIR + "/convertParameters/out";

    convertAndValidate(inputFilesPath, outputFilesPath);
  }

  @Test
  public void testConversionWithInt() throws IOException {
    String inputFilesPath = BASE_DIR + "/conversionWithInt/in";
    String outputFilesPath = BASE_DIR + "/conversionWithInt/out";

    convertAndValidate(inputFilesPath, outputFilesPath);
  }

  @Test
  public void testOccurrencesUpperString() {
    Object[] occurrences = buildOccurrences("0", UNBOUNDED);
    Assert.assertEquals(occurrences[0], 0);
    Assert.assertEquals(occurrences[1], UNBOUNDED);
  }

  @Test
  public void testOccurrencesAsInts() {
    Object[] occurrences = buildOccurrences("0", "1");
    Assert.assertEquals(occurrences[0], 0);
    Assert.assertEquals(occurrences[1], 1);
  }

  @Test
  public void testOccurrencesAsStrings() {
    String test = "TEST_A";
    Object[] occurrences = buildOccurrences(UNBOUNDED, test);
    Assert.assertEquals(occurrences[0], UNBOUNDED);
    Assert.assertEquals(occurrences[1], test);
  }

  @Test
  public void testOccurrencesLowerString() {
    Object[] occurrences = buildOccurrences(UNBOUNDED, "100");
    Assert.assertEquals(occurrences[0], UNBOUNDED);
    Assert.assertEquals(occurrences[1], 100);
  }

  @Test
  public void testOccurrencesEmpty() {
    Object[] occurrences = buildOccurrences();
    Assert.assertEquals(occurrences.length, 0);
  }

  @Test
  public void testOccurrencesMany() {
    String test = "TEST_B";
    Object[] occurrences = buildOccurrences("1", "2", test);
    Assert.assertEquals(occurrences[0], 1);
    Assert.assertEquals(occurrences[1], 2);
    Assert.assertEquals(occurrences[2], test);
  }

  @Test
  public void testDefaultOccurrences() {
    Object[] occurrences = buildOccurrences((List<String>) null);
    Assert.assertEquals(1, occurrences[0]);
    Assert.assertEquals(1, occurrences[1]);
  }

  private Object[] buildOccurrences(String... bounds) {
    return buildOccurrences(Arrays.asList(bounds));
  }

  private void convertAndValidate(String inputFilesPath, String outputFilesPath)
      throws IOException {
    FileContentHandler fileContentHandler =
        createFileContentHandlerFromInput(inputFilesPath);

    ToscaServiceModel toscaServiceModel = toscaConverter.convert(fileContentHandler);
    validateConvertorOutput(outputFilesPath, toscaServiceModel);
  }

  private void validateConvertorOutput(String outputFilesPath, ToscaServiceModel toscaServiceModel)
      throws IOException {
    ServiceTemplate mainSt = toscaServiceModel.getServiceTemplates().get(mainStName);
    Map<String, ServiceTemplate> expectedOutserviceTemplates = new HashMap<>();
    loadServiceTemplates(outputFilesPath, new ToscaExtensionYamlUtil(),
        expectedOutserviceTemplates);

    checkSTResults(expectedOutserviceTemplates, null, mainSt);
  }

  private Object[] buildOccurrences(List<String> bounds) {
    NodeType nodeType = JsonUtil.json2Object("{derived_from=tosca.nodes.Root, description=MME_VFC, " +
            "properties={vendor={type=string, default=ERICSSON}, " +
            "csarVersion={type=string, default=v1.0}, csarProvider={type=string, default=ERICSSON}, " +
            "id={type=string, default=vMME}, version={type=string, default=v1.0}, csarType={type=string, default=NFAR}}, " +
            "requirements=[{virtualLink={" +
            (bounds == null ? "" : "occurrences=[" + String.join(", ", bounds) +   "], ") +
            "capability=tosca.capabilities.network.Linkable}}]}", NodeType.class);
    List<Map<String, RequirementDefinition>> requirements = nodeType.getRequirements();
    return requirements.get(0).get(VIRTUAL_LINK).getOccurrences();
  }

  private FileContentHandler createFileContentHandlerFromInput(String inputFilesPath)
      throws IOException {
    URL inputFilesUrl = this.getClass().getResource(inputFilesPath);
    String path = inputFilesUrl.getPath();
    File directory = new File(path);
    File[] listFiles = directory.listFiles();

    FileContentHandler fileContentHandler = new FileContentHandler();
    insertFilesIntoFileContentHandler(listFiles, fileContentHandler);
    return fileContentHandler;
  }

  private void insertFilesIntoFileContentHandler(File[] listFiles,
                                                 FileContentHandler fileContentHandler)
      throws IOException {
    byte[] fileContent;
    if(CollectionUtils.isEmpty(fileContentHandler.getFileList())) {
      fileContentHandler.setFiles(new HashMap<>());
    }

    for (File file : listFiles) {
      if(!file.isDirectory()) {
        try (FileInputStream fis = new FileInputStream(file)) {
          fileContent = FileUtils.toByteArray(fis);
          fileContentHandler.addFile(file.getPath(), fileContent);
        }
      }else{
        File[] currFileList = file.listFiles();
        insertFilesIntoFileContentHandler(currFileList, fileContentHandler);
      }

    }
  }

  private void checkSTResults(
      Map<String, ServiceTemplate> expectedOutserviceTemplates,
      ServiceTemplate gloablSubstitutionServiceTemplate, ServiceTemplate mainServiceTemplate) {
    YamlUtil yamlUtil = new YamlUtil();
    if (Objects.nonNull(gloablSubstitutionServiceTemplate)) {
      assertEquals("difference global substitution service template: ",
          yamlUtil.objectToYaml(expectedOutserviceTemplates.get(globalStName)),
          yamlUtil.objectToYaml(gloablSubstitutionServiceTemplate));
    }
    if (Objects.nonNull(mainServiceTemplate)) {
      assertEquals("difference main service template: ",
          yamlUtil.objectToYaml(expectedOutserviceTemplates.get(mainStName)),
          yamlUtil.objectToYaml(mainServiceTemplate));
    }
  }

  public static void loadServiceTemplates(String serviceTemplatesPath,
                                          ToscaExtensionYamlUtil toscaExtensionYamlUtil,
                                          Map<String, ServiceTemplate> serviceTemplates)
      throws IOException {
    URL urlFile = ToscaConverterImplTest.class.getResource(serviceTemplatesPath);
    if (urlFile != null) {
      File pathFile = new File(urlFile.getFile());
      File[] files = pathFile.listFiles();
      if (files != null) {
        addServiceTemplateFiles(serviceTemplates, files, toscaExtensionYamlUtil);
      } else {
        throw new NotDirectoryException(serviceTemplatesPath);
      }
    } else {
      throw new NotDirectoryException(serviceTemplatesPath);
    }
  }

  private static void addServiceTemplateFiles(Map<String, ServiceTemplate> serviceTemplates,
                                              File[] files,
                                              ToscaExtensionYamlUtil toscaExtensionYamlUtil) throws IOException {

    for (File file : files) {

      try (InputStream yamlFile = new FileInputStream(file)) {
        ServiceTemplate serviceTemplateFromYaml =
            toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class);
        createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil);
        serviceTemplates.put(file.getName(), serviceTemplateFromYaml);
      }
    }
  }

  private static void createConcreteRequirementObjectsInServiceTemplate(ServiceTemplate
                                                                            serviceTemplateFromYaml,
                                                                        ToscaExtensionYamlUtil
                                                                            toscaExtensionYamlUtil) {

    if (serviceTemplateFromYaml == null
        || serviceTemplateFromYaml.getTopology_template() == null
        || serviceTemplateFromYaml.getTopology_template().getNode_templates() == null) {
      return;
    }

    //Creating concrete objects
    Map<String, NodeTemplate> nodeTemplates =
        serviceTemplateFromYaml.getTopology_template().getNode_templates();
    for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
      NodeTemplate nodeTemplate = entry.getValue();
      List<Map<String, RequirementAssignment>> requirements = nodeTemplate.getRequirements();
      List<Map<String, RequirementAssignment>> concreteRequirementList = new ArrayList<>();
      if (requirements != null) {
        ListIterator<Map<String, RequirementAssignment>> reqListIterator = requirements
            .listIterator();
        while (reqListIterator.hasNext()){
          Map<String, RequirementAssignment> requirement = reqListIterator.next();
          Map<String, RequirementAssignment> concreteRequirement = new HashMap<>();
          for (Map.Entry<String, RequirementAssignment> reqEntry : requirement.entrySet()) {
            RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil
                .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()),
                    RequirementAssignment.class));
            concreteRequirement.put(reqEntry.getKey(), requirementAssignment);
            concreteRequirementList.add(concreteRequirement);
            reqListIterator.remove();
          }
        }
        requirements.clear();
        requirements.addAll(concreteRequirementList);
        nodeTemplate.setRequirements(requirements);
      }
      System.out.println();
      //toscaExtensionYamlUtil.yamlToObject(nodeTemplate, NodeTemplate.class);
    }
  }
}