Add support comparable type constraints for scalar values
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / frontend / ci / tests / execute / sanity / ServiceTemplateDesignUiTests.java
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.equalToIgnoringCase;
27 import static org.hamcrest.Matchers.hasSize;
28 import static org.hamcrest.Matchers.is;
29 import static org.hamcrest.Matchers.not;
30 import static org.hamcrest.Matchers.notNullValue;
31 import static org.junit.jupiter.api.Assertions.assertEquals;
32 import static org.junit.jupiter.api.Assertions.assertNotEquals;
33 import static org.junit.jupiter.api.Assertions.assertNotNull;
34 import static org.junit.jupiter.api.Assertions.assertTrue;
35 import static org.junit.jupiter.api.Assertions.fail;
36
37 import java.io.IOException;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Optional;
45 import java.util.stream.Collectors;
46
47 import org.onap.sdc.backend.ci.tests.data.providers.OnboardingDataProviders;
48 import org.onap.sdc.backend.ci.tests.datatypes.enums.ComponentType;
49 import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum;
50 import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory;
51 import org.onap.sdc.frontend.ci.tests.datatypes.ComponentData;
52 import org.onap.sdc.frontend.ci.tests.datatypes.DirectiveType;
53 import org.onap.sdc.frontend.ci.tests.datatypes.LogicalOperator;
54 import org.onap.sdc.frontend.ci.tests.datatypes.ResourceCreateData;
55 import org.onap.sdc.frontend.ci.tests.datatypes.ServiceDependencyProperty;
56 import org.onap.sdc.frontend.ci.tests.datatypes.composition.RelationshipInformation;
57 import org.onap.sdc.frontend.ci.tests.exception.UnzipException;
58 import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory;
59 import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions;
60 import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
61 import org.onap.sdc.frontend.ci.tests.flow.AddComponentInputFlow;
62 import org.onap.sdc.frontend.ci.tests.flow.AddComponentPropertyFlow;
63 import org.onap.sdc.frontend.ci.tests.flow.AddNodeToCompositionFlow;
64 import org.onap.sdc.frontend.ci.tests.flow.CreateDirectiveNodeFilterFlow;
65 import org.onap.sdc.frontend.ci.tests.flow.CreateSubstitutionFilterFlow;
66 import org.onap.sdc.frontend.ci.tests.flow.CreateVfFlow;
67 import org.onap.sdc.frontend.ci.tests.flow.CreateVfcFlow;
68 import org.onap.sdc.frontend.ci.tests.flow.DownloadToscaTemplateFlow;
69 import org.onap.sdc.frontend.ci.tests.flow.DownloadCsarArtifactFlow;
70 import org.onap.sdc.frontend.ci.tests.flow.EditComponentPropertiesFlow;
71 import org.onap.sdc.frontend.ci.tests.flow.composition.CreateRelationshipFlow;
72 import org.onap.sdc.frontend.ci.tests.flow.exception.UiTestFlowRuntimeException;
73 import org.onap.sdc.frontend.ci.tests.pages.AttributesOutputsPage;
74 import org.onap.sdc.frontend.ci.tests.pages.ComponentPage;
75 import org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage;
76 import org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage;
77 import org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesPage;
78 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionDetailSideBarComponent;
79 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionDetailSideBarComponent.CompositionDetailTabName;
80 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionInformationTab;
81 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.InterfaceDefinitionOperationsModal;
82 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionInterfaceOperationsTab;
83 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.CompositionPage;
84 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.InterfaceDefinitionOperationsModal.InterfaceOperationsData.InputData;
85 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.RelationshipWizardInterfaceOperation.InterfaceOperationsData;
86 import org.onap.sdc.frontend.ci.tests.pages.component.workspace.ToscaArtifactsPage;
87 import org.onap.sdc.frontend.ci.tests.pages.home.HomePage;
88 import org.onap.sdc.frontend.ci.tests.utilities.FileHandling;
89 import org.openecomp.sdc.be.model.ComponentInstance;
90 import org.openqa.selenium.WebDriver;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.testng.annotations.BeforeMethod;
94 import org.testng.annotations.Test;
95 import org.yaml.snakeyaml.Yaml;
96
97 import com.aventstack.extentreports.Status;
98
99 public class ServiceTemplateDesignUiTests extends SetupCDTest {
100
101     private static final Logger LOGGER = LoggerFactory.getLogger(ServiceTemplateDesignUiTests.class);
102
103     private WebDriver webDriver;
104     private HomePage homePage;
105     private List<ResourceCreateData> vfcs = new ArrayList<>();
106     private ResourceCreateData vfResourceCreateData;
107     private ComponentInstance networkFunctionInstance;
108     private ComponentInstance networkServiceInstance;
109     private AddNodeToCompositionFlow addNodeToCompositionFlow;
110     private ComponentPage componentPage;
111     private Map<String, String> propertiesToBeAddedMap;
112     private ResourceCreatePage resourceCreatePage;
113     private Map<String, String> inputsToBeAddedMap;
114     private final List<ServiceDependencyProperty> substitutionFilterProperties = new ArrayList<>();
115     private final String interfaceName = "Standard";
116     private final String interfaceOperationName = "create";
117     private final String implementationName = "IntegrationTest";
118     private final String inputName = "InputName1";
119     private final String inputValue = "InputValue1";
120
121     @BeforeMethod
122     public void init() {
123         webDriver = DriverFactory.getDriver();
124         homePage = new HomePage(webDriver);
125     }
126
127     @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "vfcList")
128     public void importAndCertifyVfc(final String rootFolder, final String vfcFilename) {
129         setLog(vfcFilename);
130         final String resourceName = ElementFactory.addRandomSuffixToName(ElementFactory.getResourcePrefix());
131         final CreateVfcFlow createVfcFlow = createVFC(rootFolder + vfcFilename, resourceName);
132         vfcs.stream().filter(vfc -> vfc.getName().startsWith(resourceName)).findFirst().orElseThrow(
133             () -> new UiTestFlowRuntimeException(String.format("VFCs List should contain a VFC with the expected name %s", resourceName)));
134         final ResourceCreatePage vfcResourceCreatePage = createVfcFlow.getLandedPage()
135             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ResourceCreatePage"));
136         vfcResourceCreatePage.isLoaded();
137         vfcResourceCreatePage.certifyComponent();
138         ExtentTestActions.takeScreenshot(Status.INFO, "vfc-certified",
139             String.format("VFC '%s' was certified", resourceName));
140     }
141
142     @Test(dependsOnMethods = "importAndCertifyVfc")
143     public void createBaseService() {
144         final CreateVfFlow createVfFlow = createVF();
145        resourceCreatePage = createVfFlow.getLandedPage()
146             .orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a ResourceCreatePage"));
147         resourceCreatePage.isLoaded();
148     }
149
150     @Test(dependsOnMethods = "createBaseService")
151     public void addComponentProperty() throws UnzipException {
152         propertiesToBeAddedMap = loadPropertiesToAdd();
153         addProperty(propertiesToBeAddedMap);
154         componentPage = addValueToProperty(loadPropertiesToEdit());
155         componentPage.isLoaded();
156         downloadAndVerifyCsarPackageAfterAddProperty(componentPage);
157     }
158
159     @Test(dependsOnMethods = "createBaseService")
160     public void addRelationshipTemplate() throws UnzipException {
161         homePage.isLoaded();
162         resourceCreatePage = (ResourceCreatePage) homePage.clickOnComponent(vfResourceCreateData.getName());
163         resourceCreatePage.isLoaded();
164         addNodeToCompositionFlow = addNodeToCompositionAndCreateRelationship();
165         final CompositionPage compositionPage = addNodeToCompositionFlow.getLandedPage()
166             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected return CompositionPage"));
167         compositionPage.isLoaded();
168         componentPage = compositionPage.goToGeneral();
169         componentPage.isLoaded();
170         downloadAndVerifyCsarPackage(componentPage);
171     }
172
173     @Test(dependsOnMethods = "addRelationshipTemplate")
174     public void createMetadataForServiceProperty() throws Exception {
175         homePage.isLoaded();
176         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
177         componentPage.isLoaded();
178         final ResourcePropertiesAssignmentPage propertiesAssignmentPage = componentPage.goToPropertiesAssignment();
179
180         propertiesAssignmentPage.isLoaded();
181         propertiesAssignmentPage.selectInputTab();
182         final var propertyName = propertiesAssignmentPage.getInputPropertyNames().get(0);
183         final var key = "Key";
184         final var value = "Test";
185         propertiesAssignmentPage.setInputPropertyMetadata(propertyName, key, value);
186
187         final var topologyTemplate = getMapEntry(downloadToscaTemplate(), "topology_template");
188         final var inputs = getMapEntry(topologyTemplate, "inputs");
189         final var serviceProperty = getMapEntry(inputs, propertyName);
190         final var servicePropertyMetadata = getMapEntry(serviceProperty, "metadata");
191         assertNotNull(servicePropertyMetadata, String.format("Metadata not found for property %s", propertyName));
192         assertEquals(servicePropertyMetadata.get(key), value, "Created service property metadata has invalid value");
193     }
194
195     @Test(dependsOnMethods = "addRelationshipTemplate")
196     public void addOutputsToVF_test() throws UnzipException, IOException {
197         homePage.isLoaded();
198         final ComponentPage resourceCreatePage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
199         resourceCreatePage.isLoaded();
200
201         final AttributesOutputsPage attributesOutputsPage = resourceCreatePage.goToAttributesOutputs();
202         attributesOutputsPage.isLoaded();
203
204         final ComponentInstance createdComponentInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
205             .orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a ComponentInstance"));
206
207         attributesOutputsPage.clickOnAttributeNavigation(createdComponentInstance.getName());
208         assertTrue(attributesOutputsPage.isAttributePresent("attr_1"));
209         attributesOutputsPage.declareOutput("attr_1");
210         attributesOutputsPage.clickOnOutputsTab();
211         assertTrue(attributesOutputsPage.isOutputPresent("attr_1"));
212
213         attributesOutputsPage.clickOnAttributesTab();
214         assertTrue(attributesOutputsPage.isAttributePresent("attr_2"));
215         attributesOutputsPage.declareOutput("attr_2");
216         attributesOutputsPage.clickOnOutputsTab();
217         assertTrue(attributesOutputsPage.isOutputPresent("attr_2"));
218
219         attributesOutputsPage.clickOnAttributesTab();
220         assertTrue(attributesOutputsPage.isAttributePresent("attr_3"));
221         attributesOutputsPage.declareOutput("attr_3");
222         attributesOutputsPage.clickOnOutputsTab();
223         assertTrue(attributesOutputsPage.isOutputPresent("attr_3"));
224
225         attributesOutputsPage.deleteOutput(createdComponentInstance.getName() + "_attr_2");
226         attributesOutputsPage.clickOnAttributesTab();
227         assertTrue(attributesOutputsPage.isAttributePresent("attr_2"));
228         attributesOutputsPage.clickOnOutputsTab();
229         assertTrue(attributesOutputsPage.isOutputDeleted("attr_2"));
230
231         attributesOutputsPage.clickOnAttributesTab();
232         ExtentTestActions.addScreenshot(Status.INFO, "AttributesTab", "The Attribute's list : ");
233
234         attributesOutputsPage.clickOnOutputsTab();
235         ExtentTestActions.addScreenshot(Status.INFO, "OutputsTab", "The Output's list : ");
236
237         Map<String, Object> yamlObject = downloadToscaArtifact(attributesOutputsPage);
238         checkMetadata(yamlObject, vfResourceCreateData);
239         checkTopologyTemplate(yamlObject);
240     }
241
242     @Test(dependsOnMethods = "addRelationshipTemplate")
243     public void updateInterfaceOperation() throws Exception {
244         homePage.isLoaded();
245         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
246         componentPage.isLoaded();
247         final CompositionPage compositionPage = componentPage.goToComposition();
248         compositionPage.isLoaded();
249         ExtentTestActions.addScreenshot(Status.INFO, "select-VFC-node", "Selecting Node on composition");
250         compositionPage.selectNode(vfcs.get(1).getName());
251         final List<InputData> inputList = List.of(
252             new InputData("My_IT_InputName", "string", "My_IT_InputValue")
253         );
254         final InterfaceDefinitionOperationsModal.InterfaceOperationsData interfaceOperationsData =
255             new InterfaceDefinitionOperationsModal.InterfaceOperationsData("IT for updating an Interface Operation",
256                 "MyIntegrationTestImplementationName", inputList);
257         updateInterfaceOperation(compositionPage, interfaceOperationsData);
258         componentPage = compositionPage.goToGeneral();
259         componentPage.isLoaded();
260         verifyToscaTemplateHasUpdatedInterfaceOperation(downloadToscaTemplate(), interfaceOperationsData);
261     }
262
263     @Test(dependsOnMethods = "addComponentProperty")
264     public void createSubstitutionFilter() throws Exception {
265         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
266         componentPage.isLoaded();
267         loadSubstitutionFilterProperties();
268         final CompositionPage compositionPage = componentPage.goToComposition();
269         compositionPage.isLoaded();
270         substitutionFilterProperties.forEach(substitutionFilterProperty -> {
271             final CreateSubstitutionFilterFlow createSubstitutionFilterFlow = new CreateSubstitutionFilterFlow(webDriver, substitutionFilterProperty);
272             createSubstitutionFilterFlow.run(compositionPage);
273         });
274         componentPage = compositionPage.goToGeneral();
275         componentPage.isLoaded();
276         verifyToscaTemplateHasSubstitutionFilter(downloadToscaTemplate());
277     }
278
279     @Test(dependsOnMethods = "createBaseService")
280     public void createDirectiveNodeFilterTest() throws Exception {
281         final ResourceCreateData vfcResourceCreateData = vfcs.get(1);
282         final String vfcNameInComposition = vfcResourceCreateData.getName().concat(" 0");
283         final String value = "Test";
284         final LogicalOperator operator = LogicalOperator.EQUALS;
285         homePage.isLoaded();
286         componentPage = (ComponentPage) homePage.clickOnComponent(vfcResourceCreateData.getName());
287
288         componentPage.isLoaded();
289         final ResourcePropertiesPage vfcPropertiesPage = componentPage.goToProperties();
290         vfcPropertiesPage.isLoaded();
291         final Map<String, String> propertyNamesAndTypes = vfcPropertiesPage.getPropertyNamesAndTypes();
292         final List<String> propertyNames = propertyNamesAndTypes.keySet().stream().collect(Collectors.toList());
293         final ServiceDependencyProperty serviceDependencyProperty =
294                 new ServiceDependencyProperty(propertyNames.get(0), propertyNamesAndTypes.get(propertyNames.get(0)), value, operator);
295
296         homePage.getTopNavComponent().clickOnHome();
297         homePage.isLoaded();
298         homePage.clickOnComponent(vfResourceCreateData.getName());
299
300         componentPage.isLoaded();
301         final CompositionPage compositionPage = componentPage.goToComposition();
302         compositionPage.isLoaded();
303         compositionPage.selectNode(vfcNameInComposition);
304
305         final CreateDirectiveNodeFilterFlow createDirectiveNodeFilterFlow =
306                 new CreateDirectiveNodeFilterFlow(webDriver, 2, serviceDependencyProperty);
307         createDirectiveNodeFilterFlow.run(componentPage);
308
309         verifyAvailableDirectiveTypes(createDirectiveNodeFilterFlow.getDirectiveOptions());
310
311         verifyAvailablePropertyNames(propertyNames, createDirectiveNodeFilterFlow.getPropertyOptions());
312
313         componentPage = compositionPage.goToGeneral();
314         componentPage.isLoaded();
315         final Map<?, ?> yaml = downloadToscaTemplate();
316         verifyToscaTemplateHasDirectiveNodeFilter(yaml, serviceDependencyProperty, vfcNameInComposition);
317     }
318
319     @Test(dependsOnMethods = "addComponentProperty")
320     public void declareInputFromProperties() throws Exception {
321         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
322         componentPage.isLoaded();
323
324         ResourcePropertiesAssignmentPage propertiesAssignmentPage = componentPage.goToPropertiesAssignment();
325         propertiesAssignmentPage.isLoaded();
326
327         declareInputToBaseService(propertiesAssignmentPage, "property1");
328         declareInputToInstanceProperties(propertiesAssignmentPage, "resourceSubtype");
329         verifyToscaTemplateHasDeclareInput(downloadToscaTemplate());
330     }
331
332     @Test(dependsOnMethods = "createBaseService")
333     public void addComponentInputs() throws Exception {
334         inputsToBeAddedMap = loadInputsToAdd();
335         addInput(inputsToBeAddedMap);
336         verifyToscaTemplateAddInput(downloadToscaTemplate());
337     }
338
339     private void checkMetadata(final Map<String, Object> map, final ResourceCreateData createdData) {
340         final Map<String, Object> metadata = getMapEntry(map, "metadata");
341
342         assertEquals(createdData.getName(), metadata.get("name"));
343         assertEquals(createdData.getDescription(), metadata.get("description"));
344         assertEquals("Generic", metadata.get("category"));
345         assertThat((String) metadata.get("type"), not(emptyString()));
346         assertEquals(createdData.getCategory(), metadata.get("subcategory"));
347         assertEquals(createdData.getVendorName(), metadata.get("resourceVendor"));
348         assertEquals(createdData.getVendorRelease(), metadata.get("resourceVendorRelease"));
349         assertEquals(createdData.getVendorModelNumber(), metadata.get("reourceVendorModelNumber"));
350     }
351
352     private void checkTopologyTemplate(final Map<String, Object> map) {
353         final Map<String, Object> mapEntry = getMapEntry(map, "topology_template");
354         assertNotNull(mapEntry);
355
356         final Map<String, Object> inputs = getMapEntry(mapEntry, "inputs");
357         assertThat(inputs, not(anEmptyMap()));
358
359         final Map<String, Object> outputs = getMapEntry(mapEntry, "outputs");
360         assertThat(outputs, not(anEmptyMap()));
361         assertEquals(2, outputs.keySet().stream().filter(s -> (s.contains("_attr_1") || s.contains("_attr_3")) && !s.contains("_attr_2")).count());
362
363         final Map<String, Object> nodeTemplates = getMapEntry(mapEntry, "node_templates");
364         assertThat(nodeTemplates, not(anEmptyMap()));
365
366         final Map<String, Object> substitutionMappings = getMapEntry(mapEntry, "substitution_mappings");
367         assertThat(substitutionMappings, not(anEmptyMap()));
368
369         final Map<String, Object> attributes = getMapEntry(substitutionMappings, "attributes");
370         assertThat(attributes, not(anEmptyMap()));
371         assertEquals(2, attributes.keySet().stream().filter(s -> (s.contains("_attr_1") || s.contains("_attr_3")) && !s.contains("_attr_2")).count());
372     }
373
374     /**
375      * Updates an Interface operation from a selected Node (VFC)
376      * @param compositionPage the composition page
377      * @param interfaceOperationsData the interface definition
378      * @throws IOException
379      */
380     private void updateInterfaceOperation(final CompositionPage compositionPage,
381         final InterfaceDefinitionOperationsModal.InterfaceOperationsData interfaceOperationsData) throws IOException {
382         final CompositionDetailSideBarComponent detailSideBar = compositionPage.getDetailSideBar();
383         detailSideBar.isLoaded();
384         final CompositionInterfaceOperationsTab compositionInterfaceOperationsTab =
385             (CompositionInterfaceOperationsTab) detailSideBar.selectTab(CompositionDetailTabName.INTERFACE_OPERATIONS);
386         compositionInterfaceOperationsTab.isLoaded();
387         ExtentTestActions.takeScreenshot(Status.INFO, "compositionInterfaceOperationsTab",
388             "Composition Interface Operations Tab loaded");
389         assertTrue(compositionInterfaceOperationsTab.isOperationPresent(interfaceOperationName));
390         final InterfaceDefinitionOperationsModal compositionInterfaceOperationsModal = compositionInterfaceOperationsTab
391             .clickOnOperation(interfaceOperationName);
392         compositionInterfaceOperationsModal.isLoaded();
393         ExtentTestActions.takeScreenshot(Status.INFO, "update-interface-operation-modal", "Loading Interface Operations Modal");
394         compositionInterfaceOperationsModal.updateInterfaceOperation(interfaceOperationsData);
395         compositionInterfaceOperationsTab.isLoaded();
396         ExtentTestActions.addScreenshot(Status.INFO, "updated-interface-operation",
397             "The Interface operation from the selected Node was successfully updated");
398         // Gives time for UI to load the Updated Interface Operation
399         final CompositionInformationTab compositionInformationTab =
400             (CompositionInformationTab) detailSideBar.selectTab(CompositionDetailTabName.INFORMATION);
401         compositionInformationTab.isLoaded();
402         validateUpdatedInterfaceOperation(detailSideBar, interfaceOperationsData);
403     }
404
405     /**
406      * Validates if the Updated Interface Operation has the expected values
407      * @param detailSideBar The composition Page
408      * @param interfaceOperationsData The Updated Interface Definition
409      */
410     private void validateUpdatedInterfaceOperation(final CompositionDetailSideBarComponent detailSideBar,
411                                                    final InterfaceDefinitionOperationsModal.InterfaceOperationsData interfaceOperationsData) {
412         final CompositionInterfaceOperationsTab compositionInterfaceOperationsTab = (CompositionInterfaceOperationsTab) detailSideBar
413             .selectTab(CompositionDetailTabName.INTERFACE_OPERATIONS);
414         compositionInterfaceOperationsTab.isLoaded();
415         assertTrue(compositionInterfaceOperationsTab.isOperationPresent(interfaceOperationName));
416         assertTrue(compositionInterfaceOperationsTab.isDescriptionPresent());
417         final InterfaceDefinitionOperationsModal compositionInterfaceOperationsModal = compositionInterfaceOperationsTab
418             .clickOnOperation(interfaceOperationName);
419         compositionInterfaceOperationsModal.isLoaded();
420         ExtentTestActions.takeScreenshot(Status.INFO, "validate-updated-interface-operation",
421             "Loading the Interface Operations Modal for validating");
422         assertThat("The Interface Operation Description should match", interfaceOperationsData.getDescription(),
423             equalToIgnoringCase(compositionInterfaceOperationsModal.getDescription()));
424         assertThat("The Interface Operation Implementation Name should match", interfaceOperationsData.getImplementationName(),
425             equalToIgnoringCase(compositionInterfaceOperationsModal.getImplementationName()));
426 //        assertThat("The Interface Operation Input key should match", interfaceOperationsData.getInputName(),
427 //            equalToIgnoringCase(compositionInterfaceOperationsModal.getInputName()));
428 //        assertThat("The Interface Operation Input Value should match", interfaceOperationsData.getInputValue(),
429 //            equalToIgnoringCase(compositionInterfaceOperationsModal.getInputValue()));
430         compositionInterfaceOperationsModal.clickOnCancel();
431     }
432
433     private void verifyToscaTemplateHasUpdatedInterfaceOperation(final Map<?, ?> toscaTemplateYaml,
434         final InterfaceDefinitionOperationsModal.InterfaceOperationsData interfaceOperationsData) {
435
436         assertNotNull(toscaTemplateYaml, "No contents in TOSCA Template");
437         final Map<String, Object> topologyTemplateTosca = getMapEntry((Map<String, Object>) toscaTemplateYaml, "topology_template");
438         assertThat("Should contain a topology_template entry", toscaTemplateYaml, is(notNullValue()));
439         final Map<String, Object> nodeTemplatesTosca = getMapEntry(topologyTemplateTosca, "node_templates");
440         assertThat("Should contain a node_templates entry", nodeTemplatesTosca, is(notNullValue()));
441         final Optional<Entry<String, Object>> nodeWithInterfaceOperation = nodeTemplatesTosca.entrySet().stream()
442             .filter(s -> s.getKey().startsWith(vfcs.get(1).getName())).findFirst();
443         assertThat("Should contain a node (VFC)", nodeWithInterfaceOperation.isPresent(), is(true));
444         final Map<String, Object> interfacesEntry = (Map<String, Object>) nodeWithInterfaceOperation.get().getValue();
445         assertThat("The Interfaces Entry should not be empty", interfacesEntry, not(anEmptyMap()));
446         final Map<String, Object> interfaceOperations = (Map<String, Object>) interfacesEntry.get("interfaces");
447         assertThat("The Interface Entry should have operations", interfaceOperations, not(anEmptyMap()));
448         final Map<String, Object> interfaceNameMap = (Map<String, Object>) interfaceOperations.get(interfaceName);
449         assertThat(String.format("'%s' should contain a Interface Name entry '%s'", interfaceNameMap, interfaceName),
450             interfaceOperations, not(anEmptyMap()));
451         final Map<String, Object> updatedInterfaceOperation = (Map<String, Object>) interfaceNameMap.get(interfaceOperationName);
452         assertThat(String.format("'%s' should contain a Interface Operation Name '%s'", updatedInterfaceOperation, interfaceOperationName),
453             updatedInterfaceOperation, not(anEmptyMap()));
454         assertThat("The Interface Operation Description should match",
455             updatedInterfaceOperation.get("description").equals(interfaceOperationsData.getDescription()));
456         assertThat("The Interface Operation Implementation Name should match",
457             updatedInterfaceOperation.get("implementation").equals(interfaceOperationsData.getImplementationName()));
458         final Map<String, Object> updatedInterfaceOperationInput = (Map<String, Object>) updatedInterfaceOperation.get("inputs");
459         interfaceOperationsData.getInputList().forEach(inputData -> {
460             assertThat("The Interface Operation Input Key should match",
461                 updatedInterfaceOperationInput.containsKey(inputData.getName()));
462             assertThat("The Interface Operation Input Value should match",
463                 updatedInterfaceOperationInput.containsValue(inputData.getValue()));
464         });
465     }
466
467     private Map<String, Object> downloadToscaArtifact(final ComponentPage resourceCreatePage) throws UnzipException {
468         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = downloadToscaCsar(resourceCreatePage);
469         final ToscaArtifactsPage toscaArtifactsPage = downloadCsarArtifactFlow.getLandedPage()
470             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ToscaArtifactsPage"));
471
472         assertThat("No artifact download was found", toscaArtifactsPage.getDownloadedArtifactList(), not(empty()));
473         final String downloadedCsarName = toscaArtifactsPage.getDownloadedArtifactList().get(0);
474         final String downloadFolderPath = getConfig().getDownloadAutomationFolder();
475         final Map<String, byte[]> filesFromZip = FileHandling.getFilesFromZip(downloadFolderPath, downloadedCsarName);
476         final Optional<String> resourceEntryOpt = filesFromZip.keySet().stream()
477             .filter(s -> s.equals("Definitions/" + downloadedCsarName.replace("-csar.csar", "-template.yml")))
478             .findFirst();
479         if (resourceEntryOpt.isEmpty()) {
480             fail("Could not find the resource package in Definitions");
481         }
482         return loadYamlObject(filesFromZip.get(resourceEntryOpt.get()));
483     }
484
485     private void declareInputToBaseService(ResourcePropertiesAssignmentPage propertiesAssignmentPage, String propertyName){
486         propertiesAssignmentPage.selectProperty(propertyName);
487         propertiesAssignmentPage.clickOnDeclareInput();
488         propertiesAssignmentPage.clickInputTab(propertyName);
489         propertiesAssignmentPage.isInputPresent(vfResourceCreateData.getName() + "_" + propertyName);
490     }
491
492     private void declareInputToInstanceProperties(ResourcePropertiesAssignmentPage propertiesAssignmentPage, String propertyName){
493         propertiesAssignmentPage.selectPropertiesTab();
494         propertiesAssignmentPage.loadCompositionTab();
495         propertiesAssignmentPage.loadComponentInstanceProperties(vfcs.get(0).getName().concat(" 0"));
496         propertiesAssignmentPage.selectProperty(propertyName);
497         propertiesAssignmentPage.clickOnDeclareInput();
498         propertiesAssignmentPage.clickInputTab(propertyName);
499         propertiesAssignmentPage.isInputPresent(vfResourceCreateData.getName() + "_" + vfcs.get(0).getName());
500     }
501
502     private CreateVfFlow createVF() {
503         final ResourceCreateData vfCreateData = createVfFormData();
504         final CreateVfFlow createVfFlow = new CreateVfFlow(webDriver, vfCreateData);
505         createVfFlow.run(homePage);
506         return createVfFlow;
507     }
508
509     private ResourceCreateData createVfFormData() {
510         vfResourceCreateData = new ResourceCreateData();
511         vfResourceCreateData.setRandomName(ElementFactory.getResourcePrefix() + "-VF");
512         vfResourceCreateData.setCategory(ResourceCategoryEnum.GENERIC_ABSTRACT.getSubCategory());
513         vfResourceCreateData.setTagList(Arrays.asList(vfResourceCreateData.getName(), "createVF"));
514         vfResourceCreateData.setDescription("aDescription");
515         vfResourceCreateData.setVendorName("EST");
516         vfResourceCreateData.setVendorRelease("4.1.1");
517         vfResourceCreateData.setVendorModelNumber("0001");
518         return vfResourceCreateData;
519     }
520
521     private CreateVfcFlow createVFC(final String vfcFullFilename, final String resourceName) {
522         final ResourceCreateData vfcCreateData = createVfcFormData(resourceName);
523         final CreateVfcFlow createVfcFlow = new CreateVfcFlow(webDriver, vfcCreateData, vfcFullFilename);
524         createVfcFlow.run(homePage);
525         ExtentTestActions.takeScreenshot(Status.INFO, "vfc-created", String.format("VFC '%s' was created", resourceName));
526         assertThat(vfcs, notNullValue());
527         vfcs.add(vfcCreateData);
528         return createVfcFlow;
529     }
530
531     private ResourceCreateData createVfcFormData(final String resourceName) {
532         final ResourceCreateData vfcCreateData = new ResourceCreateData();
533         vfcCreateData.setRandomName(resourceName);
534         vfcCreateData.setCategory(ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory());
535         vfcCreateData.setTagList(Arrays.asList(vfcCreateData.getName(), "importVFC"));
536         vfcCreateData.setDescription("aDescription");
537         vfcCreateData.setVendorName("EST");
538         vfcCreateData.setVendorRelease("4.1.1");
539         vfcCreateData.setVendorModelNumber("0001");
540         return vfcCreateData;
541     }
542
543     private AddNodeToCompositionFlow addNodeToCompositionAndCreateRelationship() {
544         assertThat(vfcs, hasSize(2));
545         final ComponentData parentComponent = new ComponentData();
546         parentComponent.setName(vfResourceCreateData.getName());
547         parentComponent.setVersion("0.1");
548         parentComponent.setComponentType(ComponentType.RESOURCE);
549
550         // Adds networkFunction to VF composition
551         final ComponentData networkFunction = new ComponentData();
552         networkFunction.setName(vfcs.get(0).getName());
553         networkFunction.setVersion("1.0");
554         networkFunction.setComponentType(ComponentType.RESOURCE);
555         final CompositionPage compositionPage = resourceCreatePage.goToComposition();
556         compositionPage.isLoaded();
557         AddNodeToCompositionFlow addNodeToCompositionFlow = addNodeToComposition(parentComponent, networkFunction, compositionPage);
558         networkFunctionInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
559             .orElseThrow(() -> new UiTestFlowRuntimeException("Could not get the created component instance"));
560
561         // Adds networkService to VF composition
562         final ComponentData networkService = new ComponentData();
563         networkService.setName(vfcs.get(1).getName());
564         networkService.setVersion("1.0");
565         networkService.setComponentType(ComponentType.RESOURCE);
566         addNodeToCompositionFlow = addNodeToComposition(parentComponent, networkService, compositionPage);
567         networkServiceInstance = addNodeToCompositionFlow.getCreatedComponentInstance()
568             .orElseThrow(() -> new UiTestFlowRuntimeException("Could not get the created component instance"));
569
570         // Creates a dependsOn relationship from networkServiceInstance to networkFunctionInstance
571         createRelationship(compositionPage, networkFunctionInstance.getName(), "tosca.capabilities.Node",
572             networkServiceInstance.getName(), "tosca.capabilities.Node");
573
574         return addNodeToCompositionFlow;
575     }
576
577     public AddNodeToCompositionFlow addNodeToComposition(final ComponentData parentComponent,
578                                                          final ComponentData resourceToAdd,
579                                                          CompositionPage compositionPage) {
580         final AddNodeToCompositionFlow addNodeToCompositionFlow = new AddNodeToCompositionFlow(webDriver, parentComponent, resourceToAdd);
581         compositionPage = (CompositionPage) addNodeToCompositionFlow.run(compositionPage)
582             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected CompositionPage"));
583         compositionPage.isLoaded();
584         ExtentTestActions.takeScreenshot(Status.INFO, "node-added-to-composition",
585             String.format("Resource '%s' was added to composition", resourceToAdd.getName()));
586         return addNodeToCompositionFlow;
587     }
588
589     /**
590      * Creates a DependsOn relationship between the imported VFCs
591      * @param compositionPage Composition Page
592      * @param fromComponentInstanceName VFC - Network Function
593      * @param fromCapability Node Capability
594      * @param toComponentInstanceName  VFC - Network Service
595      * @param toRequirement Node Requirement
596      */
597     private void createRelationship(final CompositionPage compositionPage, final String fromComponentInstanceName,
598                                     final String fromCapability, final String toComponentInstanceName, final String toRequirement) {
599         final RelationshipInformation relationshipInformation =
600             new RelationshipInformation(fromComponentInstanceName, fromCapability, toComponentInstanceName, toRequirement);
601         final CreateRelationshipFlow createRelationshipFlow = new CreateRelationshipFlow(webDriver, relationshipInformation,
602             new InterfaceOperationsData(interfaceName, interfaceOperationName, implementationName, inputName, inputValue));
603         createRelationshipFlow.run(compositionPage).orElseThrow(() -> new UiTestFlowRuntimeException("Expecting a CompositionPage instance"));
604         ExtentTestActions.takeScreenshot(Status.INFO, "relationship",
605             String.format("Relationship from networkFunctionInstance '%s' to networkServiceInstanceResource '%s' was created",
606                 fromComponentInstanceName, toComponentInstanceName));
607     }
608
609     /**
610      * Adds a property to the base service
611      * @param propertyMap map of properties to be added
612      */
613     private void addProperty(final Map<String, String> propertyMap) {
614         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
615         componentPage.isLoaded();
616         final AddComponentPropertyFlow addComponentPropertyFlow = new AddComponentPropertyFlow(webDriver, propertyMap);
617         addComponentPropertyFlow.run(componentPage.goToPropertiesAssignment());
618     }
619
620     /**
621      * Adds a input to the base service
622      * @param inputMap map of inputs to be added
623      */
624     private void addInput(final Map<String, String> inputMap) {
625         componentPage = (ComponentPage) homePage.clickOnComponent(vfResourceCreateData.getName());
626         componentPage.isLoaded();
627         final AddComponentInputFlow addComponentInputFlow = new AddComponentInputFlow(webDriver, inputMap);
628         addComponentInputFlow.run(componentPage.goToPropertiesAssignment());
629     }
630
631     /**
632      * Edits a property to add a value
633      * @param propertyMap map of properties to be edited
634      */
635     private ComponentPage addValueToProperty(final Map<String, Object> propertyMap) {
636         final EditComponentPropertiesFlow editComponentPropertiesFlow = new EditComponentPropertiesFlow(webDriver, propertyMap);
637         return editComponentPropertiesFlow.run().orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected return ComponentPage"));
638     }
639
640     /**
641      * Downloads and verifies the generated tosca templates.
642      * @param componentPage the component page
643      * @throws UnzipException
644      */
645     private void downloadAndVerifyCsarPackage(final ComponentPage componentPage) throws UnzipException {
646         checkCsarPackage(downloadCsarPackage(componentPage));
647     }
648
649     /**
650      * Downloads and verifies if the generated Tosca template contains the expected properties.
651      * @throws UnzipException
652      * @param componentPage
653      */
654     private void downloadAndVerifyCsarPackageAfterAddProperty(final ComponentPage componentPage) throws UnzipException {
655         verifyPropertiesOnGeneratedTemplate(downloadCsarPackage(componentPage));
656     }
657
658     private String downloadCsarPackage(final ComponentPage componentPage) {
659         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = downloadToscaCsar(componentPage);
660         final ToscaArtifactsPage toscaArtifactsPage = downloadCsarArtifactFlow.getLandedPage()
661             .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected ToscaArtifactsPage"));
662         assertThat("No artifact download was found", toscaArtifactsPage.getDownloadedArtifactList(), not(empty()));
663         return toscaArtifactsPage.getDownloadedArtifactList().get(0);
664     }
665
666     /**
667      * Downloads the generated CSAR package.
668      * @param componentPage the component page
669      * @return the Downloaded Tosca CSAR file
670      */
671     private DownloadCsarArtifactFlow downloadToscaCsar(final ComponentPage componentPage) {
672         final DownloadCsarArtifactFlow downloadCsarArtifactFlow = new DownloadCsarArtifactFlow(webDriver);
673         downloadCsarArtifactFlow.setWaitBeforeGetTheFile(5L);
674         downloadCsarArtifactFlow.run(componentPage);
675         return downloadCsarArtifactFlow;
676     }
677
678     /**
679      * Verifies if the generated Tosca template contains the expected properties.
680      * @param downloadedCsarName the downloaded csar file name
681      * @throws UnzipException
682      */
683     private void verifyPropertiesOnGeneratedTemplate(final String downloadedCsarName) throws UnzipException {
684         final Map<String, byte[]> filesFromZip = extractFilesFromCsar(downloadedCsarName);
685         final String virtualFunctionName = vfResourceCreateData.getName().replace("-", "").toLowerCase();
686         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template-interface.yml";
687         final String interfaceTemplateFile = filesFromZip.keySet().stream()
688             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
689             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
690         final byte[] toscaInterfaceTemplateGenerated = filesFromZip.get(interfaceTemplateFile);
691         assertThat("The Generated Tosca template should not be null", toscaInterfaceTemplateGenerated, is(notNullValue()));
692         final Map<String, Object> interfaceTemplateYamlMap = loadYamlObject(toscaInterfaceTemplateGenerated);
693         final Map<String, Object> nodeTypesYamlMap = getMapEntry(interfaceTemplateYamlMap, "node_types");
694         assertThat(String.format("'%s' should contain a node_types entry", interfaceTemplateYamlMap), nodeTypesYamlMap, is(notNullValue()));
695         final Map<String, Object> properties = (Map) nodeTypesYamlMap.values().stream().filter(stringObjectEntry -> stringObjectEntry != null)
696             .collect(Collectors.toList()).get(0);
697         final Map<String, Object> propertiesFoundMap = (Map<String, Object>) properties.get("properties");
698         assertThat(String.format("The generated template file %s should contain all added properties", vfResourceTemplateFile),
699             propertiesFoundMap.keySet().containsAll(propertiesToBeAddedMap.keySet()), is(true));
700     }
701
702     /**
703      * Checks if the downloaded Tosca csar includes the node templates for the added VFCs,
704      * the generated service template declared “tosca_simple_yaml_1_3” as its Tosca version,
705      * the generated csar contains the node type definitions for the added VFCs in the Definitions directory,
706      * the interface template contains the relationship declaration
707      * @param downloadedCsarName download Tosca CSAR filename
708      * @throws UnzipException
709      */
710     private void checkCsarPackage(final String downloadedCsarName) throws UnzipException {
711         final Map<String, byte[]> filesFromZip = extractFilesFromCsar(downloadedCsarName);
712         final String virtualFunctionName = vfResourceCreateData.getName().replace("-", "").toLowerCase();
713         final List<String> expectedDefinitionFolderFileList = getExpectedDefinitionFolderFileList(virtualFunctionName);
714         final Map<String, byte[]> expectedFilesFromZipMap = filesFromZip.entrySet().parallelStream()
715             .filter(key -> expectedDefinitionFolderFileList.stream()
716                 .anyMatch(filename -> filename.equalsIgnoreCase(key.getKey()))).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
717         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template.yml";
718         final String generatedTemplateFile = expectedFilesFromZipMap.keySet().stream()
719             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
720             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
721         final byte[] toscaTemplateGenerated = filesFromZip.get(generatedTemplateFile);
722         assertThat(toscaTemplateGenerated, is(notNullValue()));
723         verifyGeneratedTemplate(toscaTemplateGenerated, generatedTemplateFile);
724         verifyNodesRelationship(expectedFilesFromZipMap, virtualFunctionName, filesFromZip);
725     }
726
727     private Map<String, byte[]> extractFilesFromCsar(final String downloadedCsarName) throws UnzipException {
728         final String downloadFolderPath = getConfig().getDownloadAutomationFolder();
729         final Map<String, byte[]> filesFromCsar = FileHandling.getFilesFromZip(downloadFolderPath, downloadedCsarName);
730         return filesFromCsar;
731     }
732
733     private void verifyGeneratedTemplate(final byte[] generatedTemplateData, final String generatedTemplateFile) {
734         final Map<String, Object> templateYamlMap = loadYamlObject(generatedTemplateData);
735         final boolean hasToscaDefinitionVersionEntry = templateYamlMap.containsKey("tosca_definitions_version");
736         assertThat(String.format("'%s' should contain tosca_definitions_version entry", generatedTemplateFile), hasToscaDefinitionVersionEntry,
737             is(true));
738         final String toscaVersion = (String) templateYamlMap.get("tosca_definitions_version");
739         assertThat(String.format("'%s' tosca_definitions_version entry should have tosca_simple_yaml_1_3 value", generatedTemplateFile),
740             toscaVersion.equalsIgnoreCase("tosca_simple_yaml_1_3"));
741         final Map<String, Object> topologyTemplateTosca = getMapEntry(templateYamlMap, "topology_template");
742         assertThat(String.format("'%s' should contain a topology_template entry", generatedTemplateFile), topologyTemplateTosca, is(notNullValue()));
743         final Map<String, Object> nodeTemplatesTosca = getMapEntry(topologyTemplateTosca, "node_templates");
744         assertThat(String.format("'%s' should contain a node_templates entry", generatedTemplateFile), nodeTemplatesTosca, is(notNullValue()));
745         final List<String> nodeTemplateFound = nodeTemplatesTosca.keySet().parallelStream().filter(s -> vfcs.stream()
746             .anyMatch(vfc -> s.startsWith(vfc.getName()))).collect(Collectors.toList());
747         assertThat(String.format("'%s' should contain the node type definitions for the added VFCs '%s'", nodeTemplatesTosca, vfcs),
748             nodeTemplateFound, hasSize(vfcs.size()));
749         verifyRelationshipTemplate(topologyTemplateTosca, generatedTemplateFile);
750     }
751
752     private void verifyRelationshipTemplate(final Map<String, Object> topologyTemplateToscaMap, final String generatedTemplateFile) {
753         final Map<String, Object> relationshipTemplateMap = getMapEntry(topologyTemplateToscaMap, "relationship_templates");
754         assertThat(String.format("'%s' should contain a topology_template entry", generatedTemplateFile), relationshipTemplateMap,
755             is(notNullValue()));
756         final String result = Arrays.asList(relationshipTemplateMap.values()).toString();
757         assertThat(String.format("'%s' should contain a DependsOn relationship", relationshipTemplateMap),
758             result.contains("tosca.relationships.DependsOn"), is(true));
759         assertThat(String.format("'%s' should contain interfaces entry", relationshipTemplateMap), result.contains("interfaces"), is(true));
760         assertThat(String.format("'%s' should contain a Interface Name entry '%s'", relationshipTemplateMap, interfaceName),
761             result.contains(interfaceName), is(true));
762         assertThat(String.format("'%s' should contain a Interface Operation Name '%s'", relationshipTemplateMap, interfaceOperationName),
763             result.contains(interfaceOperationName), is(true));
764         assertThat(String.format("'%s' should contain Implementation Name '%s'", relationshipTemplateMap, implementationName),
765             result.contains(implementationName), is(true));
766         assertThat(String.format("'%s' should contain inputs entry", relationshipTemplateMap), result.contains("inputs"), is(true));
767         assertThat(String.format("'%s' should contain Input Name '%s'", relationshipTemplateMap, inputName), result.contains(inputName),
768             is(true));
769         assertThat(String.format("'%s' should contain Input Value '%s'", relationshipTemplateMap, inputValue), result.contains(inputValue),
770             is(true));
771     }
772
773     private void verifyNodesRelationship(final Map<String, byte[]> expectedFilesFromZipMap, final String virtualFunctionName,
774                                          final Map<String, byte[]> filesFromZip) {
775         final String vfResourceTemplateFile = "Definitions/resource-" + virtualFunctionName + "-template-interface.yml";
776         final String interfaceTemplateFile = expectedFilesFromZipMap.keySet().stream()
777             .filter(filename -> filename.equalsIgnoreCase(vfResourceTemplateFile)).findFirst()
778             .orElseThrow(() -> new UiTestFlowRuntimeException(String.format("Resource template file not found %s", vfResourceTemplateFile)));
779         final byte[] toscaInterfaceTemplateGenerated = filesFromZip.get(interfaceTemplateFile);
780         assertThat(toscaInterfaceTemplateGenerated, is(notNullValue()));
781         final Map<String, Object> interfaceTemplateYamlMap = loadYamlObject(toscaInterfaceTemplateGenerated);
782         final Map<String, Object> nodeTypesYamlMap = getMapEntry(interfaceTemplateYamlMap, "node_types");
783         assertThat(String.format("'%s' should contain a node_types entry", interfaceTemplateYamlMap), nodeTypesYamlMap, is(notNullValue()));
784         final String result = Arrays.asList(nodeTypesYamlMap.values()).toString();
785         assertThat(String.format("'%s' should contain a capabilities entry", nodeTypesYamlMap), result.contains("capabilities"), is(true));
786         assertThat(String.format("'%s' should contain a requirements entry", nodeTypesYamlMap), result.contains("requirements"), is(true));
787         assertThat(String.format("'%s' should contain a relationship entry", nodeTypesYamlMap), result.contains("relationship"), is(true));
788         assertThat(String.format("'%s' should contain a DependsOn relationship value", nodeTypesYamlMap),
789             result.contains("tosca.relationships.DependsOn"), is(true));
790     }
791
792     private List<String> getExpectedDefinitionFolderFileList(final String vfResourceName) {
793         final List<String> expectedDefinitionFolderFileList = new ArrayList<>();
794         vfcs.forEach(vfc -> expectedDefinitionFolderFileList.add("Definitions/resource-" + vfc.getName() + "-template.yml"));
795         expectedDefinitionFolderFileList.add("Definitions/resource-" + vfResourceName + "-template.yml");
796         expectedDefinitionFolderFileList.add("Definitions/resource-" + vfResourceName + "-template-interface.yml");
797         return expectedDefinitionFolderFileList;
798     }
799
800     private void verifyToscaTemplateHasDeclareInput(Map<?, ?> yaml) {
801         assertNotNull(yaml, "No contents in TOSCA Template");
802         final Map<String, Object> toscaYaml = (Map<String, Object>) yaml;
803         final Map<String, Object> topologyTemplateTosca = getMapEntry(toscaYaml, "topology_template");
804         assertThat(String.format("'%s' should contain a topology_template entry", toscaYaml), topologyTemplateTosca,
805             notNullValue());
806         final Map<String, Object> inputsTosca = getMapEntry(topologyTemplateTosca, "inputs");
807         assertThat(String.format("'%s' should contain a inputs entry", toscaYaml), inputsTosca, notNullValue());
808         assertEquals(2, inputsTosca.keySet().stream()
809             .filter(s -> (s.contains("resourceSubtype") || s.contains("property1"))).count());
810         final Map<String, Object> substitutionMapping = getMapEntry(topologyTemplateTosca, "substitution_mappings");
811         assertThat(String.format("'%s' should contain a substitution_mappings entry", toscaYaml), substitutionMapping,
812             notNullValue());
813         final Map<String, Object> substitutionMappingProperties = getMapEntry(substitutionMapping, "properties");
814         assertThat(String.format("'%s' should contain a properties entry", toscaYaml), substitutionMappingProperties,
815             notNullValue());
816         assertEquals(2, substitutionMappingProperties.keySet().stream()
817             .filter(s -> (s.contains("resourceSubtype") || s.contains("property1"))).count());
818     }
819
820     private void verifyToscaTemplateAddInput(Map<?, ?> yaml) {
821         final Map<String, String> inputMap = loadInputsToAdd();
822         assertNotNull(yaml, "No contents in TOSCA Template");
823         final Map<String, Object> toscaYaml = (Map<String, Object>) yaml;
824         final Map<String, Object> topologyTemplateTosca = getMapEntry(toscaYaml, "topology_template");
825         assertThat(String.format("'%s' should contain a topology_template entry", toscaYaml), topologyTemplateTosca,
826             notNullValue());
827         final Map<String, Object> inputsTosca = getMapEntry(topologyTemplateTosca, "inputs");
828         assertThat(String.format("'%s' should contain a inputs entry", toscaYaml), inputsTosca, notNullValue());
829         assertEquals(3, inputsTosca.keySet().stream()
830             .filter(s -> inputMap.containsKey(s)).count());
831     }
832
833     private Map<String, Object> getMapEntry(final Map<?, ?> yamlObj, final String entryName) {
834         try {
835             return (Map<String, Object>) yamlObj.get(entryName);
836         } catch (final Exception e) {
837             final String errorMsg = String.format("Could not get the '%s' entry.", entryName);
838             LOGGER.error(errorMsg, e);
839             fail(errorMsg + "Error message: " + e.getMessage());
840         }
841         return null;
842     }
843
844     private Map<String, Object> loadYamlObject(final byte[] definitionYamlFile) {
845         return new Yaml().load(new String(definitionYamlFile));
846     }
847
848     private Map<String, String> loadPropertiesToAdd() {
849         final Map<String, String> propertyMap = new HashMap<>();
850         propertyMap.put("property1", "string");
851         propertyMap.put("property2", "integer");
852         propertyMap.put("property3", "boolean");
853         propertyMap.put("property4", "list");
854         propertyMap.put("property5", "map");
855         propertyMap.put("property6", "scalar-unit.size");
856         return propertyMap;
857     }
858
859     private Map<String, Object> loadPropertiesToEdit() {
860         final Map<String, Object> propertyMap = new HashMap<>();
861         propertyMap.put("property1", "Integration Test");
862         propertyMap.put("property2", 100);
863         propertyMap.put("property3", Boolean.TRUE);
864         propertyMap.put("property4", Arrays.asList("PropListV1", "PropListV2", "PropListV3"));
865         final Map<String, String> stringMap = new HashMap<>();
866         stringMap.put("PropMapKey1", "PropMapValue1");
867         stringMap.put("PropMapKey2", "PropMapValue2");
868         stringMap.put("PropMapKey3", "PropMapValue3");
869         propertyMap.put("property5", stringMap);
870         propertyMap.put("property6", "500 GB");
871         return propertyMap;
872     }
873
874     private Map<String, String> loadInputsToAdd() {
875         final Map<String, String> inputMap = new HashMap<>();
876         inputMap.put("input1", "string");
877         inputMap.put("input2", "integer");
878         inputMap.put("input3", "boolean");
879         return inputMap;
880     }
881
882     private void loadSubstitutionFilterProperties() {
883         final ResourcePropertiesAssignmentPage propertiesPage = componentPage.goToPropertiesAssignment();
884         propertiesPage.isLoaded();
885         ExtentTestActions.takeScreenshot(Status.INFO, "propertiesAssigment",
886             String.format("The %s Properties Assignment Page is loaded", vfResourceCreateData.getName()));
887         Map<String, String> propertyNamesAndTypes = propertiesPage.getPropertyNamesAndTypes();
888         assertThat(String.format("The Component '%s' should have properties", vfResourceCreateData.getName()), propertyNamesAndTypes,
889             not(anEmptyMap()));
890         propertyNamesAndTypes.forEach((name, type)
891             -> substitutionFilterProperties.add(new ServiceDependencyProperty(name, type, getPropertyValueByType(type), LogicalOperator.EQUALS)));
892     }
893
894     private String getPropertyValueByType(final String type) {
895         switch (type) {
896             case "string":
897                 return "IntegrationTest";
898             case "integer":
899                 return "202";
900             case "size":
901                 return "500";
902             case "boolean":
903                 return "TRUE";
904             case "list":
905                 return "[\"value1\", \"value2\"]";
906             case "map":
907                 return "{\"MyKey\": \"MyValue\"}";
908             default:
909                 throw new UnsupportedOperationException("Not yet implemented for " + type);
910         }
911     }
912
913     /**
914      * Downloads Tosca Template file
915      * @return the tosca template yaml file
916      * @throws Exception
917      */
918     private Map<?, ?> downloadToscaTemplate() throws Exception {
919         final DownloadToscaTemplateFlow downloadToscaTemplateFlow = new DownloadToscaTemplateFlow(webDriver);
920         final ToscaArtifactsPage toscaArtifactsPage = (ToscaArtifactsPage) downloadToscaTemplateFlow.run(componentPage).get();
921         return FileHandling.parseYamlFile(getConfig().getDownloadAutomationFolder()
922             .concat(java.io.File.separator).concat(toscaArtifactsPage.getDownloadedArtifactList().get(0)));
923     }
924
925     private void verifyToscaTemplateHasSubstitutionFilter(final Map<?, ?> yaml) {
926         assertNotNull(yaml, "No contents in TOSCA Template");
927         final List<?> substitutionFilters = (List<?>) getSubstitutionFilterFromYaml(yaml).get("properties");
928         substitutionFilterProperties.forEach(substitutionFilterProperty -> {
929             final Map<?, ?> substitutionFilterMap = (Map<?, ?>) substitutionFilters.stream()
930                 .filter(subFilter -> ((Map<?, ?>) subFilter).containsKey(substitutionFilterProperty.getName())).findAny().get();
931             assertThat("Added substitution filter not found in TOSCA Template",
932                 substitutionFilterMap.containsKey(substitutionFilterProperty.getName()));
933             final Map<?, ?> substitutionFilterValue = (Map<?, ?>) ((List<?>) substitutionFilterMap.get(substitutionFilterProperty.getName())).get(0);
934             assertThat("Substitution Filter Value should not be empty", substitutionFilterMap, not(anEmptyMap()));
935             final String expectedSubstitutionPropertyValue = substitutionFilterProperty.getValue().replaceAll("[\"{}]", "");
936             final String actualSubstitutionPropertyValue = substitutionFilterValue.values().stream().findFirst().get() instanceof Map
937                 ? substitutionFilterValue.values().stream().findFirst().get().toString().replace("=", ": ")
938                 .replaceAll("\\{(.*?)\\}", "$1").trim()
939                 : substitutionFilterValue.values().stream().findFirst().get().toString();
940             assertThat("Invalid value for added substitution filters found in TOSCA Template",
941                 expectedSubstitutionPropertyValue.equalsIgnoreCase(actualSubstitutionPropertyValue));
942             assertThat("Invalid logical operator for added substitution filters found in TOSCA Template",
943                 substitutionFilterValue.containsKey(substitutionFilterProperty.getLogicalOperator().getName()));
944         });
945     }
946
947     private Map<?, ?> getSubstitutionFilterFromYaml(final Map<?, ?> yaml) {
948         final Map<?, ?> topology = (Map<?, ?>) yaml.get("topology_template");
949         final Map<?, ?> substitutionMappings = (Map<?, ?>) topology.get("substitution_mappings");
950         return (Map<?, ?>) substitutionMappings.get("substitution_filter");
951     }
952
953     private void verifyAvailableDirectiveTypes(final List<String> availableDirectiveTypes) {
954         assertNotNull(availableDirectiveTypes, "Expected list of available Directive Types, but recieved null");
955         Arrays.asList(DirectiveType.values()).forEach(directiveType -> {
956             assertTrue(availableDirectiveTypes.contains(directiveType.getName())
957                     , String.format("Expected directive %s to be availabe in UI options %s"
958                             , directiveType.getName(), availableDirectiveTypes.toString()));
959         });
960         ExtentTestActions.log(Status.PASS, "All expected directive types are available for selection");
961     }
962
963     private void verifyAvailablePropertyNames(List<String> propertyNames, List<String> propertyNameOptions) {
964         assertEquals(propertyNameOptions.size(), propertyNames.size(), "Mismatch in the number of properties available for selection");
965         propertyNames.forEach(name -> {
966             assertNotEquals(false, propertyNameOptions.remove(name)
967                     , String.format("Expected property %s not found in UI Select element", name));
968         });
969         ExtentTestActions.log(Status.PASS, "All expected properties are available for selection");
970     }
971
972     private void verifyToscaTemplateHasDirectiveNodeFilter(final Map<?, ?> yaml, ServiceDependencyProperty nodeFilterProperty, String nodeTemplateName) {
973         assertNotNull(yaml, "Tosca Template Yaml is not expected to be empty");
974         final List<?> nodeFilters = (List<?>) getDirectiveNodeFilterFromYaml(yaml, nodeTemplateName).get("properties");
975         final Map<?, ?> nodeFilter = (Map<?, ?>) nodeFilters.stream()
976                     .filter(yamlNodeFilter -> ((Map<?, ?>) yamlNodeFilter).containsKey(nodeFilterProperty.getName())).findAny().get();
977         assertNotNull(nodeFilter, "Added directive node filter not found in TOSCA Template");
978
979         final Map<?, ?> nodeFilterValue = (Map<?, ?>) ((List<?>) nodeFilter.get(nodeFilterProperty.getName())).get(0);
980         assertTrue(nodeFilterValue.containsValue(nodeFilterProperty.getValue())
981                 , "Invalid value for added directive node filter found in TOSCA Template");
982         assertTrue(nodeFilterValue.containsKey(nodeFilterProperty.getLogicalOperator().getName())
983                 , "Invalid logical operator for added directive node filter found in TOSCA Template");
984     }
985
986     private Map<?,?> getDirectiveNodeFilterFromYaml(final Map<?,?> yaml, String nodeTemplateName) {
987         final Map<?, ?> topology = (Map<?, ?>) yaml.get("topology_template");
988         final Map<?, ?> nodeTemplates = (Map<?, ?>) topology.get("node_templates");
989         final Map<?, ?> resourceNode = (Map<?, ?>) nodeTemplates.get(nodeTemplateName);
990         return (Map<?, ?>) resourceNode.get("node_filter");
991     }
992 }