578edbe0d6b3630c012e03e580f7b98925f1d678
[sdc.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 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.onap.sdc.frontend.ci.tests.execute.sanity;
21
22 import static org.hamcrest.MatcherAssert.assertThat;
23 import static org.hamcrest.Matchers.anEmptyMap;
24 import static org.hamcrest.Matchers.empty;
25 import static org.hamcrest.Matchers.emptyString;
26 import static org.hamcrest.Matchers.hasSize;
27 import static org.hamcrest.Matchers.is;
28 import static org.hamcrest.Matchers.not;
29 import static org.hamcrest.Matchers.notNullValue;
30 import static org.junit.jupiter.api.Assertions.assertEquals;
31 import static org.junit.jupiter.api.Assertions.assertNotNull;
32 import static org.junit.jupiter.api.Assertions.assertTrue;
33 import static org.junit.jupiter.api.Assertions.fail;
34
35 import com.aventstack.extentreports.Status;
36 import java.io.IOException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Map.Entry;
43 import java.util.Optional;
44 import java.util.stream.Collectors;
45 import org.onap.sdc.backend.ci.tests.data.providers.OnboardingDataProviders;
46 import org.onap.sdc.backend.ci.tests.datatypes.enums.ComponentType;
47 import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum;
48 import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory;
49 import org.onap.sdc.frontend.ci.tests.datatypes.ComponentData;
50 import org.onap.sdc.frontend.ci.tests.datatypes.LogicalOperator;
51 import org.onap.sdc.frontend.ci.tests.datatypes.ResourceCreateData;
52 import org.onap.sdc.frontend.ci.tests.datatypes.ServiceDependencyProperty;
53 import org.onap.sdc.frontend.ci.tests.datatypes.composition.RelationshipInformation;
54 import org.onap.sdc.frontend.ci.tests.exception.UnzipException;
55 import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory;
56 import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions;
57 import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
58 import org.onap.sdc.frontend.ci.tests.flow.AddComponentPropertyFlow;
59 import org.onap.sdc.frontend.ci.tests.flow.AddNodeToCompositionFlow;
60 import org.onap.sdc.frontend.ci.tests.flow.CreateSubstitutionFilterFlow;
61 import org.onap.sdc.frontend.ci.tests.flow.CreateVfFlow;
62 import org.onap.sdc.frontend.ci.tests.flow.CreateVfcFlow;
63 import org.onap.sdc.frontend.ci.tests.flow.DownloadCsarArtifactFlow;
64 import org.onap.sdc.frontend.ci.tests.flow.DownloadToscaTemplateFlow;
65 import org.onap.sdc.frontend.ci.tests.flow.EditComponentPropertiesFlow;
66 import org.onap.sdc.frontend.ci.tests.flow.composition.CreateRelationshipFlow;
67 import org.onap.sdc.frontend.ci.tests.flow.exception.UiTestFlowRuntimeException;
68 import org.onap.sdc.frontend.ci.tests.pages.AttributesOutputsPage;
69 import org.onap.sdc.frontend.ci.tests.pages.ComponentPage;
70 import org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage;
71 import org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage;
72 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionPage;
73 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.ToscaArtifactsPage;
74 import org.onap.sdc.frontend.ci.tests.pages.home.HomePage;
75 import org.onap.sdc.frontend.ci.tests.utilities.FileHandling;
76 import org.openecomp.sdc.be.model.ComponentInstance;
77 import org.openqa.selenium.WebDriver;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import org.testng.annotations.BeforeMethod;
81 import org.testng.annotations.Test;
82 import org.yaml.snakeyaml.Yaml;
83
84 public class ServiceTemplateDesignUiTests extends SetupCDTest {
85
86     private static final Logger LOGGER = LoggerFactory.getLogger(ServiceTemplateDesignUiTests.class);
87
88     private WebDriver webDriver;
89     private HomePage homePage;
90     private List<ResourceCreateData> vfcs = new ArrayList<>();
91     private ResourceCreateData vfResourceCreateData;
92     private ComponentInstance networkFunctionInstance;
93     private ComponentInstance networkServiceInstance;
94     private AddNodeToCompositionFlow addNodeToCompositionFlow;
95     private ComponentPage componentPage;
96     private Map<String, String> propertiesToBeAddedMap;
97     private final List<ServiceDependencyProperty> substitutionFilterProperties = new ArrayList<>();
98
99     @BeforeMethod
100     public void init() {
101         webDriver = DriverFactory.getDriver();
102         homePage = new HomePage(webDriver);
103     }
104
105     @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "vfcList")
106     public void importAndCertifyVfc(final String rootFolder, final String vfcFilename) {
107         setLog(vfcFilename);
108         final String resourceName = ElementFactory.addRandomSuffixToName(ElementFactory.getResourcePrefix());
109         final CreateVfcFlow createVfcFlow = createVFC(rootFolder + vfcFilename, resourceName);
110         vfcs.stream().filter(vfc -> vfc.getName().startsWith(resourceName)).findFirst().orElseThrow(
111             () -> new UiTestFlowRuntimeException(String.format("VFCs List should contain a VFC with the expected name %s", resourceName)));
112         final ResourceCreatePage vfcResourceCreatePage = createVfcFlow.getLandedPage()
113             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ResourceCreatePage"));
114         vfcResourceCreatePage.isLoaded();
115         vfcResourceCreatePage.certifyComponent();
116         ExtentTestActions.takeScreenshot(Status.INFO, "vfc-certified",
117             String.format("VFC '%s' was certified", resourceName));
118     }
119
120     @Test(dependsOnMethods = "importAndCertifyVfc")
121     public void createBaseService() throws UnzipException {
122         final CreateVfFlow createVfFlow = createVF();
123         addNodeToCompositionFlow = addNodeToCompositionAndCreateRelationship(createVfFlow);
124         final CompositionPage compositionPage = addNodeToCompositionFlow.getLandedPage()
125             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected return CompositionPage"));
126         compositionPage.isLoaded();
127         componentPage = compositionPage.goToGeneral();
128         componentPage.isLoaded();
129         downloadAndVerifyCsarPackageAfterBaseServiceCreation(componentPage);
130     }
131
132     @Test(dependsOnMethods = "createBaseService")
133     public void addComponentProperty() throws UnzipException {
134         propertiesToBeAddedMap = loadPropertiesToAdd();
135         addProperty(propertiesToBeAddedMap);
136         componentPage = addValueToProperty(loadPropertiesToEdit());
137         componentPage.isLoaded();
138         downloadAndVerifyCsarPackageAfterAddProperty(componentPage);
139     }
140
141     @Test(dependsOnMethods = "createBaseService")
142     public void addOutputsToVF_test() throws UnzipException, IOException {
143         homePage.isLoaded();
144         final ComponentPage resourceCreatePage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
145         resourceCreatePage.isLoaded();
146
147         final AttributesOutputsPage attributesOutputsPage = resourceCreatePage.goToAttributesOutputs();
148         attributesOutputsPage.isLoaded();
149
150         final ComponentInstance createdComponentInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
151             .orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a ComponentInstance"));
152
153         attributesOutputsPage.clickOnAttributeNavigation(createdComponentInstance.getName());
154         assertTrue(attributesOutputsPage.isAttributePresent("attr_1"));
155         attributesOutputsPage.declareOutput("attr_1");
156         attributesOutputsPage.clickOnOutputsTab();
157         assertTrue(attributesOutputsPage.isOutputPresent("attr_1"));
158
159         attributesOutputsPage.clickOnAttributesTab();
160         assertTrue(attributesOutputsPage.isAttributePresent("attr_2"));
161         attributesOutputsPage.declareOutput("attr_2");
162         attributesOutputsPage.clickOnOutputsTab();
163         assertTrue(attributesOutputsPage.isOutputPresent("attr_2"));
164
165         attributesOutputsPage.clickOnAttributesTab();
166         assertTrue(attributesOutputsPage.isAttributePresent("attr_3"));
167         attributesOutputsPage.declareOutput("attr_3");
168         attributesOutputsPage.clickOnOutputsTab();
169         assertTrue(attributesOutputsPage.isOutputPresent("attr_3"));
170
171         attributesOutputsPage.deleteOutput(createdComponentInstance.getName() + "_attr_2");
172         attributesOutputsPage.clickOnAttributesTab();
173         assertTrue(attributesOutputsPage.isAttributePresent("attr_2"));
174         attributesOutputsPage.clickOnOutputsTab();
175         assertTrue(attributesOutputsPage.isOutputDeleted("attr_2"));
176
177         attributesOutputsPage.clickOnAttributesTab();
178         ExtentTestActions.addScreenshot(Status.INFO, "AttributesTab", "The Attribute's list : ");
179
180         attributesOutputsPage.clickOnOutputsTab();
181         ExtentTestActions.addScreenshot(Status.INFO, "OutputsTab", "The Output's list : ");
182
183         Map<String, Object> yamlObject = downloadToscaArtifact(attributesOutputsPage);
184         checkMetadata(yamlObject, vfResourceCreateData);
185         checkTopologyTemplate(yamlObject);
186     }
187
188
189     @Test(dependsOnMethods = "addComponentProperty")
190     public void createSubstitutionFilter() throws Exception {
191         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
192         componentPage.isLoaded();
193         loadSubstitutionFilterProperties();
194         final CompositionPage compositionPage = componentPage.goToComposition();
195         compositionPage.isLoaded();
196         substitutionFilterProperties.forEach(substitutionFilterProperty -> {
197             final CreateSubstitutionFilterFlow createSubstitutionFilterFlow = new CreateSubstitutionFilterFlow(webDriver, substitutionFilterProperty);
198             createSubstitutionFilterFlow.run(compositionPage);
199         });
200         componentPage = compositionPage.goToGeneral();
201         componentPage.isLoaded();
202         verifyToscaTemplateHasSubstitutionFilter(downloadToscaTemplate());
203     }
204
205     private void checkMetadata(final Map<String, Object> map, final ResourceCreateData createdData) {
206         final Map<String, Object> metadata = getMapEntry(map, "metadata");
207
208         assertEquals(createdData.getName(), metadata.get("name"));
209         assertEquals(createdData.getDescription(), metadata.get("description"));
210         assertEquals("Generic", metadata.get("category"));
211         assertThat((String) metadata.get("type"), not(emptyString()));
212         assertEquals(createdData.getCategory(), metadata.get("subcategory"));
213         assertEquals(createdData.getVendorName(), metadata.get("resourceVendor"));
214         assertEquals(createdData.getVendorRelease(), metadata.get("resourceVendorRelease"));
215         assertEquals(createdData.getVendorModelNumber(), metadata.get("reourceVendorModelNumber"));
216     }
217
218     private void checkTopologyTemplate(final Map<String, Object> map) {
219         final Map<String, Object> mapEntry = getMapEntry(map, "topology_template");
220         assertNotNull(mapEntry);
221
222         final Map<String, Object> inputs = getMapEntry(mapEntry, "inputs");
223         assertThat(inputs, not(anEmptyMap()));
224
225         final Map<String, Object> outputs = getMapEntry(mapEntry, "outputs");
226         assertThat(outputs, not(anEmptyMap()));
227         assertEquals(2, outputs.keySet().stream().filter(s -> (s.contains("_attr_1") || s.contains("_attr_3")) && !s.contains("_attr_2")).count());
228
229         final Map<String, Object> nodeTemplates = getMapEntry(mapEntry, "node_templates");
230         assertThat(nodeTemplates, not(anEmptyMap()));
231
232         final Map<String, Object> substitutionMappings = getMapEntry(mapEntry, "substitution_mappings");
233         assertThat(substitutionMappings, not(anEmptyMap()));
234
235         final Map<String, Object> attributes = getMapEntry(substitutionMappings, "attributes");
236         assertThat(attributes, not(anEmptyMap()));
237         assertEquals(2, attributes.keySet().stream().filter(s -> (s.contains("_attr_1") || s.contains("_attr_3")) && !s.contains("_attr_2")).count());
238     }
239
240     private Map<String, Object> downloadToscaArtifact(final ComponentPage resourceCreatePage) throws UnzipException {
241         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = downloadToscaCsar(resourceCreatePage);
242         final ToscaArtifactsPage toscaArtifactsPage = downloadCsarArtifactFlow.getLandedPage()
243             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ToscaArtifactsPage"));
244
245         assertThat("No artifact download was found", toscaArtifactsPage.getDownloadedArtifactList(), not(empty()));
246         final String downloadedCsarName = toscaArtifactsPage.getDownloadedArtifactList().get(0);
247         final String downloadFolderPath = getConfig().getDownloadAutomationFolder();
248         final Map<String, byte[]> filesFromZip = FileHandling.getFilesFromZip(downloadFolderPath, downloadedCsarName);
249         final Optional<String> resourceEntryOpt = filesFromZip.keySet().stream()
250             .filter(s -> s.equals("Definitions/" + downloadedCsarName.replace("-csar.csar", "-template.yml")))
251             .findFirst();
252         if (resourceEntryOpt.isEmpty()) {
253             fail("Could not find the resource package in Definitions");
254         }
255         return loadYamlObject(filesFromZip.get(resourceEntryOpt.get()));
256     }
257
258     private CreateVfFlow createVF() {
259         final ResourceCreateData vfCreateData = createVfFormData();
260         final CreateVfFlow createVfFlow = new CreateVfFlow(webDriver, vfCreateData);
261         createVfFlow.run(homePage);
262         return createVfFlow;
263     }
264
265     private ResourceCreateData createVfFormData() {
266         vfResourceCreateData = new ResourceCreateData();
267         vfResourceCreateData.setRandomName(ElementFactory.getResourcePrefix() + "-VF");
268         vfResourceCreateData.setCategory(ResourceCategoryEnum.GENERIC_ABSTRACT.getSubCategory());
269         vfResourceCreateData.setTagList(Arrays.asList(vfResourceCreateData.getName(), "createVF"));
270         vfResourceCreateData.setDescription("aDescription");
271         vfResourceCreateData.setVendorName("EST");
272         vfResourceCreateData.setVendorRelease("4.1.1");
273         vfResourceCreateData.setVendorModelNumber("0001");
274         return vfResourceCreateData;
275     }
276
277     private CreateVfcFlow createVFC(final String vfcFullFilename, final String resourceName) {
278         final ResourceCreateData vfcCreateData = createVfcFormData(resourceName);
279         final CreateVfcFlow createVfcFlow = new CreateVfcFlow(webDriver, vfcCreateData, vfcFullFilename);
280         createVfcFlow.run(homePage);
281         ExtentTestActions.takeScreenshot(Status.INFO, "vfc-created", String.format("VFC '%s' was created", resourceName));
282         assertThat(vfcs, notNullValue());
283         vfcs.add(vfcCreateData);
284         return createVfcFlow;
285     }
286
287     private ResourceCreateData createVfcFormData(final String resourceName) {
288         final ResourceCreateData vfcCreateData = new ResourceCreateData();
289         vfcCreateData.setRandomName(resourceName);
290         vfcCreateData.setCategory(ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory());
291         vfcCreateData.setTagList(Arrays.asList(vfcCreateData.getName(), "importVFC"));
292         vfcCreateData.setDescription("aDescription");
293         vfcCreateData.setVendorName("EST");
294         vfcCreateData.setVendorRelease("4.1.1");
295         vfcCreateData.setVendorModelNumber("0001");
296         return vfcCreateData;
297     }
298
299     private AddNodeToCompositionFlow addNodeToCompositionAndCreateRelationship(final CreateVfFlow createVfFlow) {
300         final ResourceCreatePage resourceCreatePage = createVfFlow.getLandedPage()
301             .orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a ResourceCreatePage"));
302         resourceCreatePage.isLoaded();
303         assertThat(vfcs, hasSize(2));
304         final ComponentData parentComponent = new ComponentData();
305         parentComponent.setName(vfResourceCreateData.getName());
306         parentComponent.setVersion("0.1");
307         parentComponent.setComponentType(ComponentType.RESOURCE);
308
309         // Adds networkFunction to VF composition
310         final ComponentData networkFunction = new ComponentData();
311         networkFunction.setName(vfcs.get(0).getName());
312         networkFunction.setVersion("1.0");
313         networkFunction.setComponentType(ComponentType.RESOURCE);
314         CompositionPage compositionPage = resourceCreatePage.goToComposition();
315         compositionPage.isLoaded();
316         AddNodeToCompositionFlow addNodeToCompositionFlow = addNodeToComposition(parentComponent, networkFunction, compositionPage);
317         networkFunctionInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
318             .orElseThrow(() -> new UiTestFlowRuntimeException("Could not get the created component instance"));
319
320         // Adds networkService to VF composition
321         final ComponentData networkService = new ComponentData();
322         networkService.setName(vfcs.get(1).getName());
323         networkService.setVersion("1.0");
324         networkService.setComponentType(ComponentType.RESOURCE);
325         addNodeToCompositionFlow = addNodeToComposition(parentComponent, networkService, compositionPage);
326         networkServiceInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
327             .orElseThrow(() -> new UiTestFlowRuntimeException("Could not get the created component instance"));
328
329         // Creates a dependsOn relationship from networkServiceInstance to networkFunctionInstance
330         createRelationship(compositionPage, networkFunctionInstance.getName(), "tosca.capabilities.Node",
331             networkServiceInstance.getName(), "tosca.capabilities.Node");
332
333         return addNodeToCompositionFlow;
334     }
335
336     public AddNodeToCompositionFlow addNodeToComposition(final ComponentData parentComponent,
337                                                          final ComponentData resourceToAdd,
338                                                          CompositionPage compositionPage) {
339         final AddNodeToCompositionFlow addNodeToCompositionFlow = new AddNodeToCompositionFlow(webDriver, parentComponent, resourceToAdd);
340         compositionPage = (CompositionPage) addNodeToCompositionFlow.run(compositionPage)
341             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected CompositionPage"));
342         compositionPage.isLoaded();
343         ExtentTestActions.takeScreenshot(Status.INFO, "node-added-to-composition",
344             String.format("Resource '%s' was added to composition", resourceToAdd.getName()));
345         return addNodeToCompositionFlow;
346     }
347
348     /**
349      * Creates a DependsOn relationship between the imported VFCs
350      * @param compositionPage Composition Page
351      * @param fromComponentInstanceName VFC - Network Function
352      * @param fromCapability Node Capability
353      * @param toComponentInstanceName  VFC - Network Service
354      * @param toRequirement Node Requirement
355      */
356     private void createRelationship(final CompositionPage compositionPage, final String fromComponentInstanceName,
357                                     final String fromCapability, final String toComponentInstanceName, final String toRequirement) {
358         final RelationshipInformation relationshipInformation =
359             new RelationshipInformation(fromComponentInstanceName, fromCapability, toComponentInstanceName, toRequirement);
360         CreateRelationshipFlow createRelationshipFlow = new CreateRelationshipFlow(webDriver, relationshipInformation);
361         createRelationshipFlow.run(compositionPage).orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a CompositionPage instance"));
362         ExtentTestActions.takeScreenshot(Status.INFO, "relationship",
363             String.format("Relationship from networkFunctionInstance '%s' to networkServiceInstanceResource '%s' was created",
364                 fromComponentInstanceName, toComponentInstanceName));
365     }
366
367     /**
368      * Adds a property to the base service
369      * @param propertyMap map of properties to be added
370      */
371     private void addProperty(final Map<String, String> propertyMap) {
372         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
373         componentPage.isLoaded();
374         final AddComponentPropertyFlow addComponentPropertyFlow = new AddComponentPropertyFlow(webDriver, propertyMap);
375         addComponentPropertyFlow.run(componentPage.goToPropertiesAssignment());
376     }
377
378     /**
379      * Edits a property to add a value
380      * @param propertyMap map of properties to be edited
381      */
382     private ComponentPage addValueToProperty(final Map<String, Object> propertyMap) {
383         final EditComponentPropertiesFlow editComponentPropertiesFlow = new EditComponentPropertiesFlow(webDriver, propertyMap);
384         return editComponentPropertiesFlow.run().orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected return ComponentPage"));
385     }
386
387     /**
388      * Downloads and verifies the generated tosca templates.
389      * @param componentPage the component page
390      * @throws UnzipException
391      */
392     private void downloadAndVerifyCsarPackageAfterBaseServiceCreation(final ComponentPage componentPage) throws UnzipException {
393         checkCsarPackage(downloadCsarPackage(componentPage));
394     }
395
396     /**
397      * Downloads and verifies if the generated Tosca template contains the expected properties.
398      * @throws UnzipException
399      * @param componentPage
400      */
401     private void downloadAndVerifyCsarPackageAfterAddProperty(final ComponentPage componentPage) throws UnzipException {
402         verifyPropertiesOnGeneratedTemplate(downloadCsarPackage(componentPage));
403     }
404
405     private String downloadCsarPackage(final ComponentPage componentPage) {
406         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = downloadToscaCsar(componentPage);
407         final ToscaArtifactsPage toscaArtifactsPage = downloadCsarArtifactFlow.getLandedPage()
408             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ToscaArtifactsPage"));
409         assertThat("No artifact download was found", toscaArtifactsPage.getDownloadedArtifactList(), not(empty()));
410         return toscaArtifactsPage.getDownloadedArtifactList().get(0);
411     }
412
413     /**
414      * Downloads the generated CSAR package.
415      * @param componentPage the component page
416      * @return the Downloaded Tosca CSAR file
417      */
418     private DownloadCsarArtifactFlow downloadToscaCsar(final ComponentPage componentPage) {
419         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = new DownloadCsarArtifactFlow(webDriver);
420         downloadCsarArtifactFlow.setWaitBeforeGetTheFile(5L);
421         downloadCsarArtifactFlow.run(componentPage);
422         return downloadCsarArtifactFlow;
423     }
424
425     /**
426      * Verifies if the generated Tosca template contains the expected properties.
427      * @param downloadedCsarName the downloaded csar file name
428      * @throws UnzipException
429      */
430     private void verifyPropertiesOnGeneratedTemplate(final String downloadedCsarName) throws UnzipException {
431         final Map<String, byte[]> filesFromZip = extractFilesFromCsar(downloadedCsarName);
432         final String virtualFunctionName = vfResourceCreateData.getName().replace("-", "").toLowerCase();
433         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template-interface.yml";
434         final String interfaceTemplateFile = filesFromZip.keySet().stream()
435             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
436             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
437         final byte[] toscaInterfaceTemplateGenerated = filesFromZip.get(interfaceTemplateFile);
438         assertThat("The Generated Tosca template should not be null", toscaInterfaceTemplateGenerated, is(notNullValue()));
439         final Map<String, Object> interfaceTemplateYamlMap = loadYamlObject(toscaInterfaceTemplateGenerated);
440         final Map<String, Object> nodeTypesYamlMap = getMapEntry(interfaceTemplateYamlMap, "node_types");
441         assertThat(String.format("'%s' should contain a node_types entry", interfaceTemplateYamlMap), nodeTypesYamlMap, is(notNullValue()));
442         final Map<String, Object> properties = (Map) nodeTypesYamlMap.values().stream().filter(stringObjectEntry -> stringObjectEntry != null)
443             .collect(Collectors.toList()).get(0);
444         final Map<String, Object> propertiesFoundMap = (Map<String, Object>) properties.get("properties");
445         assertThat(String.format("The generated template file %s should contain all added properties", vfResourceTemplateFile),
446             propertiesFoundMap.keySet().containsAll(propertiesToBeAddedMap.keySet()), is(true));
447     }
448
449     /**
450      * Checks if the downloaded Tosca csar includes the node templates for the added VFCs,
451      * the generated service template declared “tosca_simple_yaml_1_3” as its Tosca version,
452      * the generated csar contains the node type definitions for the added VFCs in the Definitions directory,
453      * the interface template contains the relationship declaration
454      * @param downloadedCsarName download Tosca CSAR filename
455      * @throws UnzipException
456      */
457     private void checkCsarPackage(final String downloadedCsarName) throws UnzipException {
458         final Map<String, byte[]> filesFromZip = extractFilesFromCsar(downloadedCsarName);
459         final String virtualFunctionName = vfResourceCreateData.getName().replace("-", "").toLowerCase();
460         final List<String> expectedDefinitionFolderFileList = getExpectedDefinitionFolderFileList(virtualFunctionName);
461         final Map<String, byte[]> expectedFilesFromZipMap = filesFromZip.entrySet().parallelStream()
462             .filter(key -> expectedDefinitionFolderFileList.stream()
463                 .anyMatch(filename -> filename.equalsIgnoreCase(key.getKey()))).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
464         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template.yml";
465         final String generatedTemplateFile = expectedFilesFromZipMap.keySet().stream()
466             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
467             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
468         final byte[] toscaTemplateGenerated = filesFromZip.get(generatedTemplateFile);
469         assertThat(toscaTemplateGenerated, is(notNullValue()));
470         verifyGeneratedTemplate(toscaTemplateGenerated, generatedTemplateFile);
471         verifyNodesRelationship(expectedFilesFromZipMap, virtualFunctionName, filesFromZip);
472     }
473
474     private Map<String, byte[]> extractFilesFromCsar(final String downloadedCsarName) throws UnzipException {
475         final String downloadFolderPath = getConfig().getDownloadAutomationFolder();
476         final Map<String, byte[]> filesFromCsar = FileHandling.getFilesFromZip(downloadFolderPath, downloadedCsarName);
477         return filesFromCsar;
478     }
479
480     private void verifyGeneratedTemplate(final byte[] generatedTemplateData, final String generatedTemplateFile) {
481         final Map<String, Object> templateYamlMap = loadYamlObject(generatedTemplateData);
482         final boolean hasToscaDefinitionVersionEntry = templateYamlMap.containsKey("tosca_definitions_version");
483         assertThat(String.format("'%s' should contain tosca_definitions_version entry", generatedTemplateFile), hasToscaDefinitionVersionEntry,
484             is(true));
485         final String toscaVersion = (String) templateYamlMap.get("tosca_definitions_version");
486         assertThat(String.format("'%s' tosca_definitions_version entry should have tosca_simple_yaml_1_3 value", generatedTemplateFile),
487             toscaVersion.equalsIgnoreCase("tosca_simple_yaml_1_3"));
488         final Map<String, Object> topologyTemplateTosca = getMapEntry(templateYamlMap, "topology_template");
489         assertThat(String.format("'%s' should contain a topology_template entry", generatedTemplateFile), topologyTemplateTosca, is(notNullValue()));
490         final Map<String, Object> nodeTemplatesTosca = getMapEntry(topologyTemplateTosca, "node_templates");
491         assertThat(String.format("'%s' should contain a node_templates entry", generatedTemplateFile), nodeTemplatesTosca, is(notNullValue()));
492         final List<String> nodeTemplateFound = nodeTemplatesTosca.keySet().parallelStream().filter(s -> vfcs.stream()
493             .anyMatch(vfc -> s.startsWith(vfc.getName()))).collect(Collectors.toList());
494         assertThat(String.format("'%s' should contain the node type definitions for the added VFCs '%s'", nodeTemplatesTosca, vfcs),
495             nodeTemplateFound, hasSize(vfcs.size()));
496     }
497
498     private void verifyNodesRelationship(final Map<String, byte[]> expectedFilesFromZipMap, final String virtualFunctionName,
499                                          final Map<String, byte[]> filesFromZip) {
500         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template-interface.yml";
501         final String interfaceTemplateFile = expectedFilesFromZipMap.keySet().stream()
502             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
503             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
504         final byte[] toscaInterfaceTemplateGenerated = filesFromZip.get(interfaceTemplateFile);
505         assertThat(toscaInterfaceTemplateGenerated, is(notNullValue()));
506         final Map<String, Object> interfaceTemplateYamlMap = loadYamlObject(toscaInterfaceTemplateGenerated);
507         final Map<String, Object> nodeTypesYamlMap = getMapEntry(interfaceTemplateYamlMap, "node_types");
508         assertThat(String.format("'%s' should contain a node_types entry", interfaceTemplateYamlMap), nodeTypesYamlMap, is(notNullValue()));
509         final String result = Arrays.asList(nodeTypesYamlMap.values()).toString();
510         assertThat(String.format("'%s' should contain a capabilities entry", nodeTypesYamlMap), result.contains("capabilities"), is(true));
511         assertThat(String.format("'%s' should contain a requirements entry", nodeTypesYamlMap), result.contains("requirements"), is(true));
512         assertThat(String.format("'%s' should contain a relationship entry", nodeTypesYamlMap), result.contains("relationship"), is(true));
513         assertThat(String.format("'%s' should contain a DependsOn relationship value", nodeTypesYamlMap),
514             result.contains("tosca.relationships.DependsOn"), is(true));
515     }
516
517     private List<String> getExpectedDefinitionFolderFileList(final String vfResourceName) {
518         final List<String> expectedDefinitionFolderFileList = new ArrayList<>();
519         vfcs.forEach(vfc -> expectedDefinitionFolderFileList.add("Definitions/resource-" + vfc.getName() + "-template.yml"));
520         expectedDefinitionFolderFileList.add("Definitions/resource-" + vfResourceName + "-template.yml");
521         expectedDefinitionFolderFileList.add("Definitions/resource-" + vfResourceName + "-template-interface.yml");
522         return expectedDefinitionFolderFileList;
523     }
524
525     private Map<String, Object> getMapEntry(final Map<String, Object> yamlObj, final String entryName) {
526         try {
527             return (Map<String, Object>) yamlObj.get(entryName);
528         } catch (final Exception e) {
529             final String errorMsg = String.format("Could not get the '%s' entry.", entryName);
530             LOGGER.error(errorMsg, e);
531             fail(errorMsg + "Error message: " + e.getMessage());
532         }
533         return null;
534     }
535
536     private Map<String, Object> loadYamlObject(final byte[] definitionYamlFile) {
537         return new Yaml().load(new String(definitionYamlFile));
538     }
539
540     private Map<String, String> loadPropertiesToAdd() {
541         final Map<String, String> propertyMap = new HashMap<>();
542         propertyMap.put("property1", "string");
543         propertyMap.put("property2", "integer");
544         propertyMap.put("property3", "boolean");
545         propertyMap.put("property4", "list");
546         propertyMap.put("property5", "map");
547         propertyMap.put("property6", "scalar-unit.size");
548         return propertyMap;
549     }
550
551     private Map<String, Object> loadPropertiesToEdit() {
552         final Map<String, Object> propertyMap = new HashMap<>();
553         propertyMap.put("property1", "Integration Test");
554         propertyMap.put("property2", 100);
555         propertyMap.put("property3", Boolean.TRUE);
556         propertyMap.put("property4", Arrays.asList("PropListV1", "PropListV2", "PropListV3"));
557         final Map<String, String> stringMap = new HashMap<>();
558         stringMap.put("PropMapKey1", "PropMapValue1");
559         stringMap.put("PropMapKey2", "PropMapValue2");
560         stringMap.put("PropMapKey3", "PropMapValue3");
561         propertyMap.put("property5", stringMap);
562         propertyMap.put("property6", 500);
563         return propertyMap;
564     }
565
566     private void loadSubstitutionFilterProperties() {
567         final ResourcePropertiesAssignmentPage propertiesPage = componentPage.goToPropertiesAssignment();
568         propertiesPage.isLoaded();
569         ExtentTestActions.takeScreenshot(Status.INFO, "propertiesAssigment",
570             String.format("The %s Properties Assignment Page is loaded", vfResourceCreateData.getName()));
571         Map<String, String> propertyNamesAndTypes = propertiesPage.getPropertyNamesAndTypes();
572         assertThat(String.format("The Component '%s' should have properties", vfResourceCreateData.getName()), propertyNamesAndTypes,
573             not(anEmptyMap()));
574         propertyNamesAndTypes.forEach((name, type)
575             -> substitutionFilterProperties.add(new ServiceDependencyProperty(name, getPropertyValueByType(type), LogicalOperator.EQUALS)));
576     }
577
578     private String getPropertyValueByType(final String type) {
579         switch (type) {
580             case "string":
581                 return "IntegrationTest";
582             case "integer":
583                 return "202";
584             case "size":
585                 return "500";
586             case "boolean":
587                 return "TRUE";
588             case "list":
589                 return "[value1, value2]";
590             case "map":
591                 return "MyKey: MyValue";
592             default:
593                 throw new UnsupportedOperationException("Not yet implemented for " + type);
594         }
595     }
596
597     /**
598      * Downloads Tosca Template file
599      * @return the tosca template yaml file
600      * @throws Exception
601      */
602     private Map<?, ?> downloadToscaTemplate() throws Exception {
603         final DownloadToscaTemplateFlow downloadToscaTemplateFlow = new DownloadToscaTemplateFlow(webDriver);
604         final ToscaArtifactsPage toscaArtifactsPage = (ToscaArtifactsPage) downloadToscaTemplateFlow.run(componentPage).get();
605         return FileHandling.parseYamlFile(getConfig().getDownloadAutomationFolder()
606             .concat(java.io.File.separator).concat(toscaArtifactsPage.getDownloadedArtifactList().get(0)));
607     }
608
609     private void verifyToscaTemplateHasSubstitutionFilter(final Map<?, ?> yaml) {
610         assertNotNull(yaml, "No contents in TOSCA Template");
611         final List<?> substitutionFilters = (List<?>) getSubstitutionFilterFromYaml(yaml).get("properties");
612         substitutionFilterProperties.forEach(substitutionFilterProperty -> {
613             final Map<?, ?> substitutionFilterMap = (Map<?, ?>) substitutionFilters.stream()
614                 .filter(subFilter -> ((Map<?, ?>) subFilter).containsKey(substitutionFilterProperty.getName())).findAny().get();
615             assertThat("Added substitution filter not found in TOSCA Template",
616                 substitutionFilterMap.containsKey(substitutionFilterProperty.getName()));
617             final Map<?, ?> substitutionFilterValue = (Map<?, ?>) ((List<?>) substitutionFilterMap.get(substitutionFilterProperty.getName())).get(0);
618             assertThat("Substitution Filter Value should not be empty", substitutionFilterMap, not(anEmptyMap()));
619             final String expectedSubstitutionPropertyValue = substitutionFilterProperty.getValue();
620             final String actualSubstitutionPropertyValue = substitutionFilterValue.values().stream().findFirst().get() instanceof Map
621                 ? substitutionFilterValue.values().stream().findFirst().get().toString().replace("=", ": ")
622                 .replaceAll("\\{(.*?)\\}", "$1").trim()
623                 : substitutionFilterValue.values().stream().findFirst().get().toString();
624             assertThat("Invalid value for added substitution filters found in TOSCA Template",
625                 expectedSubstitutionPropertyValue.equalsIgnoreCase(actualSubstitutionPropertyValue));
626             assertThat("Invalid logical operator for added substitution filters found in TOSCA Template",
627                 substitutionFilterValue.containsKey(substitutionFilterProperty.getLogicalOperator().getName()));
628         });
629     }
630
631     private Map<?, ?> getSubstitutionFilterFromYaml(final Map<?, ?> yaml) {
632         final Map<?, ?> topology = (Map<?, ?>) yaml.get("topology_template");
633         final Map<?, ?> substitutionMappings = (Map<?, ?>) topology.get("substitution_mappings");
634         return (Map<?, ?>) substitutionMappings.get("substitution_filter");
635     }
636 }