diff options
Diffstat (limited to 'ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities')
18 files changed, 5697 insertions, 0 deletions
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java new file mode 100644 index 0000000000..aa260ecc80 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdditionalConditions.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.util.concurrent.TimeUnit; + +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.support.ui.ExpectedCondition; + +import com.paulhammant.ngwebdriver.NgWebDriver; + +public class AdditionalConditions { + + public static ExpectedCondition<Boolean> jQueryAJAXCallsHaveCompleted() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { + return (Boolean) ((JavascriptExecutor)driver). + executeScript("return (window.jQuery!= null) && (jQuery.active === 0);"); + } + }; + } + + public static ExpectedCondition <Boolean> angularHasFinishedProcessing() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { +// String scriptJS = "return (window.angular !==undefined) &&" +// + " (angular.element(document).injector() !==undefined) &&" +// + " (angular.element(document).injector().get('$http').pendingRequests.length === 0)"; +// return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + new NgWebDriver((JavascriptExecutor) driver).waitForAngularRequestsToFinish(); + return true; + } + }; + } + + public static ExpectedCondition <Boolean> pageLoadWait() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { + String scriptJS = + "try {\r\n" + + " if (document.readyState !== 'complete') {\r\n" + + " return false; // Page not loaded yet\r\n" + + " }\r\n" + + " if (window.jQuery) {\r\n" + + " if (window.jQuery.active) {\r\n" + + " return false;\r\n" + + " } else if (window.jQuery.ajax && window.jQuery.ajax.active) {\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " if (window.angular) {\r\n" + + " if (!window.qa) {\r\n" + + " // Used to track the render cycle finish after loading is complete\r\n" + + " window.qa = {\r\n" + + " doneRendering: false\r\n" + + " };\r\n" + + " }\r\n" + + " // Get the angular injector for this app (change element if necessary)\r\n" + + " var injector = window.angular.element('body').injector();\r\n" + + " // Store providers to use for these checks\r\n" + + " var $rootScope = injector.get('$rootScope');\r\n" + + " var $http = injector.get('$http');\r\n" + + " var $timeout = injector.get('$timeout');\r\n" + + " // Check if digest\r\n" + + " if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {\r\n" + + " window.qa.doneRendering = false;\r\n" + + " return false; // Angular digesting or loading data\r\n" + + " }\r\n" + + " if (!window.qa.doneRendering) {\r\n" + + " // Set timeout to mark angular rendering as finished\r\n" + + " $timeout(function() {\r\n" + + " window.qa.doneRendering = true;\r\n" + + " }, 0);\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " return true;\r\n" + + "} catch (ex) {\r\n" + + " return false;\r\n" + + "}"; + return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + } + }; + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java new file mode 100644 index 0000000000..db621f3355 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AdminWorkspaceUIUtilies.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.pages.AdminGeneralPage; + +public class AdminWorkspaceUIUtilies { + + + public static void createNewUser(String userId, UserRoleEnum userRole){ + AdminGeneralPage.getUserManagementTab().setNewUserBox(userId); + AdminGeneralPage.getUserManagementTab().selectUserRole(userRole); + AdminGeneralPage.getUserManagementTab().clickCreateButton(); +// AdminWorkspaceUIUtilies.highlightNewRow(); + } + + private static void highlightNewRow(){ + GeneralUIUtils.HighlightMyElement(AdminGeneralPage.getUserManagementTab().getRow(0)); + } + + public static void updateUserRole(int rowIndx, UserRoleEnum userRole) { + AdminGeneralPage.getUserManagementTab().updateUser(rowIndx); + AdminGeneralPage.getUserManagementTab().updateUserRole(userRole, rowIndx); + AdminGeneralPage.getUserManagementTab().saveAfterUpdateUser(rowIndx); + } + + public static void deleteFirstRow(){ + AdminGeneralPage.getUserManagementTab().deleteUser(0); + } + + public static void searchForUser(String searchString){ + AdminGeneralPage.getUserManagementTab().searchUser(searchString); + } + + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java new file mode 100644 index 0000000000..d55ace4374 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java @@ -0,0 +1,638 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.awt.AWTException; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders; +import org.openecomp.sdc.ci.tests.datatypes.HeatWithParametersDefinition; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage; +import org.openecomp.sdc.ci.tests.pages.UploadArtifactPopup; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class ArtifactUIUtils { + + private static final String PARAMETERS = "parameters"; + + private ArtifactUIUtils() { + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo) throws Exception { + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + fillAndAddNewArtifactParameters(artifactInfo, artifactPopup); +// artifactPopup.defineArtifactLabel(artifactInfo.getArtifactLabel()); +// artifactPopup.selectArtifactType(artifactInfo.getArtifactType()); +// artifactPopup.insertDescription(artifactInfo.getDescription()); +// artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); +// artifactPopup.clickAddButton(); + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.defineArtifactLabel(artifactInfo.getArtifactLabel()); + artifactPopup.selectArtifactType(artifactInfo.getArtifactType()); + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickDoneButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("A new artifact of type %s was added", artifactInfo.getArtifactType())); + } + + public static void fillAndAddNewEnvArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickDoneButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("ENV parameters %s artifact updated ", artifactInfo.getArtifactType())); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsPlaceholders artifactLabel,String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + InformationalArtifactPage.artifactPopup().loadFile(filepath, filename); + InformationalArtifactPage.artifactPopup().insertDescription(description); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsService artifactLabel, + String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static void fillPlaceHolderAPIArtifact(DataTestIdEnum.APIArtifactsService artifactLabel, + String filepath, String filename, String description, String url) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertURL(url); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static RestResponse deploymentArtifactResourceInUI(ResourceReqDetails resource, User user, + ArtifactReqDetails artifact, String file) throws Exception { + Thread.sleep(1000); + + List<WebElement> listFormInput = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-designer-sidebar-tab")); + WebElement addArtifactElement = listFormInput.get(2); + addArtifactElement.click(); + + WebElement addArtifact = GeneralUIUtils.getDriver() + .findElement(By.className("i-sdc-designer-sidebar-section-content-item-artifact-details-name")); + addArtifact.click(); + + Thread.sleep(1000); + WebElement descriptionProperty = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-textarea")); + descriptionProperty.clear(); + descriptionProperty.sendKeys(artifact.getDescription()); + + WebElement uploadFile = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-label-upload")); + uploadFile.click(); + + StringSelection sel = new StringSelection(file); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null); + // System.out.println("selection" + sel); + Thread.sleep(1000); + + Robot robot = new Robot(); + Thread.sleep(1000); + + Thread.sleep(2000); + + robot.keyPress(KeyEvent.VK_ENTER); + + // Release Enter + robot.keyRelease(KeyEvent.VK_ENTER); + + // Press CTRL+V + robot.keyPress(KeyEvent.VK_CONTROL); + robot.keyPress(KeyEvent.VK_V); + + // Release CTRL+V + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.keyRelease(KeyEvent.VK_V); + Thread.sleep(1000); + + // Press Enter + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + Thread.sleep(3000); + + WebElement clickDone = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-form-action")); + clickDone.click(); + + Thread.sleep(3500); + + GeneralUIUtils.getDriver().findElement(By.cssSelector("button[data-ng-click^=save]")).click(); + + RestResponse getResource = RestCDUtils.getResource(resource, user); + assertEquals("Did not succeed to get resource after create", 200, getResource.getErrorCode().intValue()); + return getResource; + } + + public static void addInformationArtifact(ArtifactReqDetails artifact, String filePath, + final InformationalArtifactsPlaceholders dataTestEnum) throws Exception { + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.sleep(2000); + GeneralUIUtils.getWebElementByTestID(dataTestEnum.getValue()).click(); + +// final WebElement browseWebElement = GeneralUIUtils.retryMethodOnException( +// () -> GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue())); + + WebElement browseWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue()); + browseWebElement.sendKeys(filePath); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.DESCRIPTION.getValue()) + .sendKeys(artifact.getDescription()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ADD.getValue()).click(); + + } + + private static void addFileToWindowBrowse(String file) throws InterruptedException, AWTException { + StringSelection sel = new StringSelection(file); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null); + // System.out.println("selection" + sel); + Thread.sleep(1000); + + Robot robot = new Robot(); + + robot.keyPress(KeyEvent.VK_ENTER); + + // Release Enter + robot.keyRelease(KeyEvent.VK_ENTER); + + // Press CTRL+V + robot.keyPress(KeyEvent.VK_CONTROL); + robot.keyPress(KeyEvent.VK_V); + + // Release CTRL+V + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.keyRelease(KeyEvent.VK_V); + Thread.sleep(1000); + + // Press Enter + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + Thread.sleep(3000); + } + + static WebElement ArtifactLabel; + + public static Map<String, String> addInformationalArtifact(String artifactLabel) throws Exception { + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + Map<String, String> artifactValues = new HashMap<String, String>(); + String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption() + .getText(); + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getAttribute("value").equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList("HEAT", "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + String fileName = "Heat-File.yaml"; + GeneralUIUtils.setWebElementByTestId("description", "description"); + ResourceUIUtils.importFileWithSendKeyBrowse(ImportAssetUIUtils.FILE_PATH, fileName); + GeneralUIUtils.getWebElementByTestID("Add").click(); + GeneralUIUtils.getWebElementByTestID(labelName); + + artifactValues.put("type", type); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + public static Map<String, String> addDeploymentArtifact(String artifactLabel, String artifactType, String fileName) + throws Exception { + String type = null; + String labelName; + Map<String, String> artifactValues = new HashMap<String, String>(); + try { + labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getOptions().get(1).getText(); + GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").selectByVisibleText(labelName); + } catch (Exception e) { + labelName = GeneralUIUtils.getWebElementByClassName(artifactLabel).getText(); + } + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getText().equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList(artifactType, "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + GeneralUIUtils.setWebElementByTestId("description", "description" ); + ResourceUIUtils.importFileWithSendKeyBrowse(ImportAssetUIUtils.FILE_PATH, fileName); + try { + GeneralUIUtils.getWebElementByTestID("Add").click(); + } catch (Exception e) { + GeneralUIUtils.getWebElementByClassName("w-sdc-form-action add-property").click(); + } + + artifactValues.put("type", artifactType); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + + public static Map<String, String> addDeploymentArtifactFromCanvas(String artifactLabel) throws Exception { + String type = null; + Map<String, String> artifactValues = new HashMap<String, String>(); + String labelName = GeneralUIUtils.getSelectList(artifactLabel, "selectArtifact").getFirstSelectedOption() + .getText(); + ArtifactLabel = GeneralUIUtils.getDriver().findElement(By.name("artifactLabel")); + if (ArtifactLabel.getText().equals("")) { + labelName = "New-Test-Artifact"; + ArtifactLabel.sendKeys(labelName); + type = GeneralUIUtils.getSelectList("OTHER", "artifacttype").getFirstSelectedOption().getText(); + } + String description = "This is Description"; + String filePath = "C:\\Git_work\\ASDC\\d2-sdnc\\ui-ci\\src\\main\\resources\\Files\\"; + String fileName = "Heat-File.yaml"; + GeneralUIUtils.setWebElementByTestId("description", "description"); + ResourceUIUtils.importFileWithSendKeyBrowse(filePath, fileName); + GeneralUIUtils.getWebElementByTestID("Add").click(); + artifactValues.put("type", type); + artifactValues.put("description", description); + artifactValues.put("name", labelName); + artifactValues.put("fileName", fileName); + return artifactValues; + } + + public static Map<String, String> valideArtifact(Map<String, String> artifactValues, Boolean condition) + throws Exception { + if (condition) { + GeneralUIUtils.getWebElementByClassName("table-edit-btn").click(); + } else { + System.out.println(artifactValues.get("name")); + GeneralUIUtils.getWebElementByTestID("edit_" + artifactValues.get("name")).click(); + } + Thread.sleep(1000); + String labelname = GeneralUIUtils.getWebElementByClassName("artifactLabel").getAttribute("value"); + String filename = GeneralUIUtils.getWebElementByTestID("filename").getText(); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", "")); + assertEquals(filename, artifactValues.get("fileName").replaceAll(" ", "-")); + assertEquals(type, artifactValues.get("type")); + assertEquals(description, artifactValues.get("description")); + GeneralUIUtils.getWebElementByTestID("Update").click(); + return artifactValues; + } + + public static void valideArtifactFromCanvas(Map<String, String> artifactValues) throws Exception { + GeneralUIUtils.getWebElementByTestID("artifactDisplayName-" + artifactValues.get("name")).click(); + Thread.sleep(1000); + String labelname = GeneralUIUtils.getWebElementByClassName("artifactLabel").getAttribute("value"); + String filename = GeneralUIUtils.getWebElementByTestID("filename").getText(); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String type = GeneralUIUtils.getSelectList(null, "artifacttype").getFirstSelectedOption().getText(); + labelname.compareToIgnoreCase(artifactValues.get("name").replaceAll("-", "")); + assertEquals(filename, artifactValues.get("fileName")); + assertEquals(type, artifactValues.get("type")); + assertEquals(description, artifactValues.get("description")); + } + + public static Map<String, Map<String, Object>> getArtifactsListFromResponse(String jsonResponse, + String fieldOfArtifactList) { + JSONObject object = (JSONObject) JSONValue.parse(jsonResponse); + Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) object.get(fieldOfArtifactList); + return map; + } + + public static void validateArtifactNameVersionType(String artifactLabel, String artifactVersion, String artifactType) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactLabel); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactLabel)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact label not equal - this warnning represent defect."); + } + if(artifactVersion != null) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactVersion, "Artifact version not equal."); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactVersion)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact version not equal - this warnning represent defect."); + } + } + if(artifactType != null) { +// Assert.assertEquals(GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactLabel + "']")).getAttribute("textContent").trim(), artifactType, "Artifact type not equal."); + if(!GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactType)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact type not equal - this warnning represent defect."); + } + } + } + + public static void validateArtifactVersionByTypeAndLabel(String artifactLabel, String expectedArtifactVersion, ArtifactTypeEnum artifactType) { + if(expectedArtifactVersion != null) { + String xPath; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to validate artifact version ...")); + if(artifactType.getType().equals(ArtifactTypeEnum.HEAT_ENV.getType())){ + xPath = "//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION_ENV.getValue() + artifactLabel + "']"; + }else{ + xPath = "//*[@data-tests-id='" + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']"; + } + String actualartifactVersion = GeneralUIUtils.getDriver().findElement(By.xpath(xPath)).getAttribute("textContent").trim(); + Assert.assertEquals(actualartifactVersion, expectedArtifactVersion, "Artifact type " + artifactType.getType() + " expected version is " + expectedArtifactVersion + " not equal to " + actualartifactVersion); + } + } + + public static void validateExistArtifactOnDeploymentInformationPage(String expectedArtifactLabel, String artifactUUID, String artifactVersion, String artifactType, boolean isDownloadable, boolean isEditable, boolean isDeletable, boolean isArtifactParametersEditable) { + + String dataTestId = DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + expectedArtifactLabel; + + List<WebElement> artifactElements = GeneralUIUtils.getWebElementsListByContainTestID(dataTestId); + Assert.assertEquals(artifactElements.size(), 1, "There are more then one artifact named " + expectedArtifactLabel); + + WebElement artifact = artifactElements.get(0); + String actualArtifactLabel = GeneralUIUtils.getTextContentAttributeValue(artifact).trim(); + Assert.assertEquals(actualArtifactLabel, expectedArtifactLabel); + + if(artifactUUID != null) { + WebElement uuid = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(uuid).trim(), artifactUUID, "Artifact uuid not equal."); + } + if(artifactVersion != null) { + WebElement version = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(version).trim(), artifactVersion, "Artifact version not equal."); + } + if(artifactType != null) { + WebElement type = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(type).trim(), artifactType, "Artifact type not equal."); + } + if(isArtifactParametersEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button enabled."); + } else if(isArtifactParametersEditable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button disabled."); + } + if(isDownloadable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button enabled."); + } else if(isDownloadable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button disabled."); + } + if(isEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button enabled."); + } else if(isEditable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button disabled."); + } + if(isDeletable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button enabled."); + } else if(isDeletable==false) { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button disabled."); + } + } + + public static void validateNotExistArtifactOnDeploymentInformationPage(String artifactLabel) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel), false); + } + + public static void validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(String fileName, String artifactDisplayedName, + boolean isUpdateable, boolean isParametersEditable, boolean isDownloadable, boolean isDeleteable) { + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName).getText(), fileName); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName).getText(), artifactDisplayedName); + + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + + if(isParametersEditable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), true, "Expect that parameters edit button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), false, "Expect that parameters edit button disabled."); + } + if(isDownloadable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), true, "Expect that download button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), false, "Expect that download button disabled."); + } + if(isDeleteable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), true, "Expect that delete button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), false, "Expect that delete button disabled."); + } + if(isUpdateable) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), true, "Expect that edit button enabled."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + GeneralUIUtils.waitForElementInVisibilityByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + } else { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false, "Expect that edit button disabled."); + } + + } + + public static void validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(String artifactDisplayedName) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName), false); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile, String dataTestId) throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(dataTestId); + return verifyUpdatedEnvParameters(pairToUpdate, updateEnvFile); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile) throws Exception { + + String heatDisplayName = pairToUpdate.getHeatArtifactDisplayName(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue()+heatDisplayName); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + + String pattern = PARAMETERS; + Map<String, Object> mapUpdetedEnvFile = FileHandling.parseYamlFileToMapByPattern(updateEnvFile, pattern); + Map<String, Object> mapDownloadedEnvFile = FileHandling.parseYamlFileToMapByPattern(latestFilefromDir, pattern); + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to check, that ENV file was updated ..."); + assertTrue("File" + latestFilefromDir.getName() + " contains different parameters number from expected file", mapDownloadedEnvFile.size() == mapUpdetedEnvFile.size()); + assertTrue("Updated file contains not updated parameters value", mapDownloadedEnvFile.entrySet().containsAll(mapUpdetedEnvFile.entrySet())); + return latestFilefromDir; + } + + /** + * compare heat env files by pattern ("parameters") + * @param expectedFile + * @param actualFile + * @param pattern + * @throws Exception + */ + public static void compareYamlFilesByPattern(File expectedFile, File actualFile, String pattern) throws Exception { + + Map<String, Object> mapExpectedFile = FileHandling.parseYamlFileToMapByPattern(expectedFile, pattern); + Map<String, Object> mapActualFile = FileHandling.parseYamlFileToMapByPattern(actualFile, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare files ..."); + assertTrue("File" + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size()); + assertTrue("File " + actualFile.getName() + " does not contains all expected parametrs", mapActualFile.entrySet().containsAll(mapExpectedFile.entrySet())); + } + + public static void compareYamlParametersByPattern(Map<String, Object> mapExpectedproperties, File actualFileproperties, String pattern) throws Exception { + + Map<String, Object> mapActualFileProerties = FileHandling.parseYamlFileToMapByPattern(actualFileproperties, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare files ..."); + assertTrue("Actual file contains different parameters number from expected file", mapActualFileProerties.size() == mapExpectedproperties.size()); + Map<String, Object> newMap = new HashMap<>(mapActualFileProerties); + assertTrue("Actual file does not contains all expected parametrs", newMap.entrySet().containsAll(mapExpectedproperties.entrySet())); + } + + + public static File uploadCreatedUpdateParametersEnvFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws Exception { +// created env file to upload + File pathToEnvParametersFile = prepareEnvParametersFile(heatEnvDetails, directoryPath); + ArtifactInfo heatEnvArtifactInfo = new ArtifactInfo(directoryPath, heatEnvDetails.getHeatEnvLabel()+".env", "heatEnvDesc", heatEnvDetails.getHeatEnvLabel(),heatEnvDetails.getHeatEnvArtifactType()); + ArtifactUIUtils.fillAndAddNewEnvArtifactParameters(heatEnvArtifactInfo, CompositionPage.artifactPopup()); + return pathToEnvParametersFile; + } + + public static File prepareEnvParametersFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws IOException { + File pathToEnvParametersFile = FileHandling.createEmptyFile(directoryPath+heatEnvDetails.getHeatEnvLabel()+".env"); +// fill file + FileHandling.writeToFile(pathToEnvParametersFile, "parameters:", 0); + for(HeatParameterDataDefinition paramDefinition : heatEnvDetails.getHeatParameterDefinition()){ + Object data = getDataToWrite(paramDefinition); + FileHandling.writeToFile(pathToEnvParametersFile, data, 2); + } + + return pathToEnvParametersFile; + } + + public static Object getDataToWrite(HeatParameterDataDefinition paramDefinition) { + Object data = ""; + switch (paramDefinition.getType()) { + case "string": + String text = "\"string\""; + data = getFormatedData(paramDefinition.getName(), text); + break; + case "number": + data = getFormatedData(paramDefinition.getName(), 666); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + data = getFormatedData(paramDefinition.getName(), jsonText); + break; + case "boolean": + if(paramDefinition.getCurrentValue().equals("true")){ + data = getFormatedData(paramDefinition.getName(), false); + }else{ + data = getFormatedData(paramDefinition.getName(), true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + data = getFormatedData(paramDefinition.getName(), commaDelimitedListText); + break; + default: + break; + } + return data; + } + + + public static Map<String, Object> getDataToWriteInUI(List<HeatParameterDataDefinition> paramDefinitionFromGetResourceResponse) { + Map<String, Object>newValuesToUpdateInUI=new HashMap<>(); + for (HeatParameterDataDefinition param : paramDefinitionFromGetResourceResponse) { + System.out.println(param.getCurrentValue()); + switch (param.getType()) { + + case "string": + String text = "string"; + newValuesToUpdateInUI.put(param.getName(),text); + break; + case "number": + newValuesToUpdateInUI.put(param.getName(),666); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + newValuesToUpdateInUI.put(param.getName(),jsonText); + break; + case "boolean": + if (param.getCurrentValue().equals(true)) { + newValuesToUpdateInUI.put(param.getName(),false); + } else { + newValuesToUpdateInUI.put(param.getName(),true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + newValuesToUpdateInUI.put(param.getName(),commaDelimitedListText); + break; + default: + break; + + } + + } + return newValuesToUpdateInUI; + } + + public static Object getValue(HeatParameterDataDefinition param) { + String type = param.getType(); + Object result = null; + switch(type){ + case "string": + result = param.getCurrentValue(); + break; + case "number": + result = new Integer(param.getCurrentValue()); + break; + case "json": + result = param.getCurrentValue(); + break; + case "boolean": + result = new Boolean(param.getCurrentValue()); + break; + case "comma_delimited_list": + result = param.getCurrentValue(); + break; + default: + break; + } + return result; + } + + public static Object getFormatedData(String name, Object text) { + return name + ": " + text; +} + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java new file mode 100644 index 0000000000..c53fef596a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject; +import org.openecomp.sdc.ci.tests.utils.general.Convertor; +import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils; + +public class AuditCDUtils { + + public static void validateResourceSuccessAudit(ResourceReqDetails resource, User user, String action) + throws Exception { + JSONObject auditBody = AuditValidationUtils.filterAuditByUuid(action, resource.getUUID()); + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor + .constructFieldsForAuditValidation(resource, resource.getVersion(), user); + String auditAction = "Create"; + expectedResourceAuditJavaObject.setAction(auditAction); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, auditBody.toString(), false); + } + + public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action) + throws Exception { + validateServiceSuccessAudit(service, user, action, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + + public static void validateServiceSuccessAudit(ServiceReqDetails service, User user, String action, + LifecycleStateEnum lifecycleStatus) throws Exception { + ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils + .constructFieldsForAuditValidation(service, service.getVersion(), user); + String body = AuditValidationUtils.filterAuditByUuid(action, service.getUUID()).toString(); + expectedResourceAuditJavaObject.setAction(action); + expectedResourceAuditJavaObject.setPrevState(""); + expectedResourceAuditJavaObject.setPrevVersion(""); + expectedResourceAuditJavaObject.setCurrState(lifecycleStatus.toString()); + expectedResourceAuditJavaObject.setStatus("201"); + expectedResourceAuditJavaObject.setDesc("OK"); + AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, action, body, false); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java new file mode 100644 index 0000000000..fbe8c04036 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasElement.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openqa.selenium.WebElement; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair<Integer, Integer> location; + private WebElement elementType; + + CanvasElement(String name, ImmutablePair<Integer, Integer> location, WebElement canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + elementType = canvasItem; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair<Integer, Integer> getLocation() { + return location; + } + + public void setLocation(ImmutablePair<Integer, Integer> location) { + this.location = location; + } + + public WebElement getElementType() { + return elementType; + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java new file mode 100644 index 0000000000..18cb338891 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CanvasManager.java @@ -0,0 +1,179 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; + +public final class CanvasManager { + private Map<String, CanvasElement> canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 40; + private static final int CANVAS_ELEMENT_X_OFFSET = 21; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List<CanvasElement> getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair<Integer, Integer> newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + Thread.sleep(500); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.waitForLoader(); + } + + private String getItemName(WebElement canvasItem) { + String canvasItemName = canvasItem.getAttribute("data-tests-id"); + + return canvasItemName.substring(canvasItemName.lastIndexOf("-")); + } + + public CanvasElement createElementOnCanvas(WebElement canvasItem) throws Exception { + GeneralUIUtils.waitForLoader(); + ImmutablePair<Integer, Integer> freePosition = getFreePosition(); + actions.moveToElement(canvasItem, 0, 0); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + + String uniqueId = getItemName(canvasItem) + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, canvasItem); + addCanvasElement(canvasElement); + GeneralUIUtils.waitForLoader(); + return canvasElement; + } + + private ImmutablePair<Integer, Integer> getFreePosition() { + // TODO mshitrit use better method + ImmutablePair<Integer, Integer> randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair<Integer, Integer> tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair<Integer, Integer> getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair<Integer, Integer>(xElement, yElement); + } + + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + GeneralUIUtils.waitForLoader(); + drawSimpleLink(firstElement, secondElement); + + selectReqAndCapAndConnect(); + + GeneralUIUtils.waitForLoader(); + + } + + private void selectReqAndCapAndConnect() { + // Select First Cap + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click(); + // Select First Req + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0).click(); + // Connect + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) { + + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, + secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java new file mode 100644 index 0000000000..e9ba11f0f4 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java @@ -0,0 +1,232 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.CatalogPageLeftPanelFilterTitle; +import org.openecomp.sdc.ci.tests.datatypes.TypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class CatalogUIUtilitis { + + + + + + // Get all Categories , Subcategories and Icons. + public void getAllCategoriesAndSubcategories() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + String subcategoryname = (String) subcategories.getJSONObject(j).get("name"); + System.out.println(subcategoryname); + } + for (int j = 0; j < subcategories.length(); j++) { + JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons"); + for (int k = 0; k < icons.length(); k++) { + System.out.println(icons.get(k)); + } + } + System.out.println("-------------------------------"); + } + } + + @Test + // FOr testing---delete. + public static List<String> abcd() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + List<String> allcat = new ArrayList<>(); + String uniqueId = null; + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + uniqueId = (String) categories.getJSONObject(i).get("uniqueId"); + allcat.add(uniqueId); + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + String subcategoryname = (String) subcategories.getJSONObject(j).get("name"); + uniqueId = (String) subcategories.getJSONObject(j).get("uniqueId"); + allcat.add(uniqueId); + } + } + return allcat; + + } + + public static void clickTopMenuButton(TopMenuButtonsEnum button) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s button ...", button.name())); + switch (button) { + case CATALOG: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case HOME: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case ON_BOARDING: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + default: + break; + } + GeneralUIUtils.ultimateWait(); + } + + public static String catalogFilterTypeChecBox(TypesEnum enumtype) throws Exception { + String Type = enumtype.toString().toLowerCase(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s ...", Type)); + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + return Type; + } + + public static List<String> catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum) throws Exception { + List<String> status = null; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s status", statusEnum.name())); + switch (statusEnum) { + case IN_DESIGN: + status = Arrays.asList("NOT_CERTIFIED_CHECKIN", "NOT_CERTIFIED_CHECKOUT"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case READY_FOR_TESTING: + status = Arrays.asList("READY_FOR_CERTIFICATION"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case IN_TESTING: + status = Arrays.asList("CERTIFICATION_IN_PROGRESS"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case CERTIFIED: + status = Arrays.asList("CERTIFIED"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + case DISTRIBUTED: + status = Arrays.asList("CERTIFIED"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + break; + } + return status; + } + + // Get all Categories uniqueID .//The parent categories. + public static List<String> getCategories() throws IOException, JSONException { + List<String> allCategoriesList = new ArrayList<>(); + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + System.out.println(categoryname); + allCategoriesList.add(categoryname); + } + return allCategoriesList; + } + + @Test + // Get Subcategories by Category name + public static List<String> getAllSubcategoriesByUniqueId(String uniqueId) throws IOException, JSONException { + + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + List<String> subCategories = new ArrayList<>();// subCategories to + // return. + JSONArray subcategories = null; + + for (int i = 0; i < categories.length(); i++) { + + String categoryuniqueId = (String) categories.getJSONObject(i).get("uniqueId"); + + if (categoryuniqueId.contentEquals(uniqueId)) { + subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + + for (int j = 0; j < subcategories.length(); j++) { + + subCategories.add((String) subcategories.getJSONObject(j).get("uniqueId")); + } + + break; + } + } + if (subcategories == null) { + subCategories.add(uniqueId); + } + return subCategories; + } + + @Test + // Get icons by category name + public void getSubCategoryIcons() throws IOException, JSONException { + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String subcategoryname = (String) categories.getJSONObject(i).get("name"); + if (subcategoryname.contentEquals("Generic")) { + JSONArray subcategories = (JSONArray) categories.getJSONObject(i).get("subcategories"); + for (int j = 0; j < subcategories.length(); j++) { + JSONArray icons = (JSONArray) subcategories.getJSONObject(j).get("icons"); + for (int k = 0; k < icons.length(); k++) { + System.out.println(icons.get(k)); + } + } + break; + } + } + } + + + public static WebElement clickOnUpperCategoryCheckbox() throws InterruptedException { + List<WebElement> categorieCheckboxes = GeneralUIUtils.getElementsByCSS("span[data-tests-id*='category']"); // get all categories and subcategories + WebElement categorieCheckbox = categorieCheckboxes.get(0); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s category ...", categorieCheckbox.getText())); + categorieCheckbox.click(); + GeneralUIUtils.ultimateWait(); + return categorieCheckbox; + } + + public static void clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle leftPanelElement) throws InterruptedException { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", leftPanelElement.name())); + GeneralUIUtils.getElementsByCSS(leftPanelElement.getValue()).forEach(WebElement::click); + } + + public static WebElement catalogSearchBox(String searchText) { + WebElement searchBox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchBox.clear(); + searchBox.sendKeys(searchText); + return searchBox; + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java new file mode 100644 index 0000000000..08b392fcd6 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/DownloadManager.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.io.File; +import java.util.List; + +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.AttFtpClient; +import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + +public class DownloadManager { + + + public File fetchDownloadedFile(){ + + File retrieveLastModifiedFileFromFTP = null; + + if (DriverFactory.getConfig().isRemoteTesting()){ + + + try { + + AttFtpClient instance = AttFtpClient.getInstance(); + AttFtpClient.getInstance().retrieveListOfFile(); + retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); + + } catch (Exception e) { + System.out.println("could not retriev file"); + } + + return retrieveLastModifiedFileFromFTP; + + } + + + return retrieveLastModifiedFileFromFTP; + + } + + + /** + * this method download csar file from VSP repository to default browser download directory + * @param vspName + * @throws Exception + */ + public static void downloadCsarByNameFromVSPRepository(String vspName, String vspId) throws Exception{ + FileHandling.cleanCurrentDownloadDir(); + HomePage.showVspRepository(); + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound){ + ExtentTestActions.log(Status.INFO, String.format("Going to downloading VSP %s", vspName)); + List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable(); +// GeneralUIUtils.ultimateWait(); +// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 5); +// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); + elemenetsFromTable.get(1).click(); +// findElement.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.DOWNLOAD_CSAR.getValue()); + ExtentTestActions.log(Status.INFO, "Succeeded to downloaded CSAR file named " + vspId + " into folder " + SetupCDTest.getWindowTest().getDownloadDirectory()); + GeneralUIUtils.getElementsByCSS("div[class^='w-sdc-modal-close']").forEach(e -> e.click()); + GeneralUIUtils.ultimateWait(); + } + } + +// AttFtpClient instance = AttFtpClient.getInstance(); +// +// String server = "135.177.130.113"; +// int port = 2121; +// String user = "admin"; +// String pass = "admin"; +// AttFtpClient.getInstance().init(server, port, user, pass); +// +// try { +// AttFtpClient.getInstance().retrieveListOfFile(); +// +// File retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); +// String content = new String(Files.readAllBytes(Paths.get(retrieveLastModifiedFileFromFTP.getPath())), StandardCharsets.UTF_8); +//// instance.deleteFilesFromFTPserver(); +// System.out.println(content); +// readFile(retrieveLastModifiedFileFromFTP); +// +// } finally { +// instance.terminateClient(); +// } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java new file mode 100644 index 0000000000..6008f200d2 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java @@ -0,0 +1,505 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.yaml.snakeyaml.Yaml; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class FileHandling { + +// ------------------yaml parser methods---------------------------- + public static Map<?, ?> parseYamlFile(String filePath) throws Exception { + Yaml yaml = new Yaml(); + File file = new File(filePath); + InputStream inputStream = new FileInputStream(file); + Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream); + return map; + } + + /** + * The method return map fetched objects by pattern from yaml file + * @param yamlFile + * @param pattern + * @return + * @throws Exception + */ + public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception { + Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString()); + Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern); + return objectMap; + } + + @SuppressWarnings("unchecked") + public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) { + Map<String, Object> objectMap = null; + + Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern); + if(objectUpdetedEnvFile instanceof HashMap){ + objectMap = (Map<String, Object>) objectUpdetedEnvFile; + } + return objectMap; + } + +// ------------------------------------------------------------------------------------------------- + + public static String getFilePath(String folder) { + String filepath = System.getProperty("filepath"); + if (filepath == null && System.getProperty("os.name").contains("Windows")) { + filepath = FileHandling.getResourcesFilesPath() + folder + File.separator; + } + + else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; + } + + System.out.println(filepath); + + return filepath; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getDriversPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci" + File.separator + "drivers" + File.separator; + } + + public static String getResourcesFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator; + } + + public static String getResourcesEnvFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator; + } + + public static String getCiFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci"; + } + + public static String getConfFilesPath() { + return getCiFilesPath() + File.separator + "conf" + File.separator; + } + + public static String getTestSuitesFilesPath() { + return getCiFilesPath() + File.separator + "testSuites" + File.separator; + } + + public static String getVnfRepositoryPath() { + return getFilePath("VNFs"); + } + + public static File getConfigFile(String configFileName) throws Exception { + File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName); + if (!configFile.exists()) { + configFile = new File(FileHandling.getConfFilesPath() + configFileName); + } + return configFile; + } + + public static Object[] filterFileNamesFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List<String> filenames = new ArrayList<String>(); + + FilenameFilter extensionFilter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(extension); + } + }; + + if (dir.isDirectory()) { + for (File file : dir.listFiles(extensionFilter)) { + filenames.add(file.getName()); + } + return filenames.toArray(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getArtifactsFromZip(String filepath, String zipFilename){ + try{ + ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + + String[] artifactNames = new String[zipFile.size() - 1]; + + int i = 0; + while(entries.hasMoreElements()){ + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()){ + if (!nextElement.getName().equals("MANIFEST.json")){ + String name = nextElement.getName(); + artifactNames[i++] = name; + } + } + } + zipFile.close(); + return artifactNames; + } + catch(ZipException zipEx){ + System.err.println("Error in zip file named : " + zipFilename); + zipEx.printStackTrace(); + } catch (IOException e) { + System.err.println("Unhandled exception : "); + e.printStackTrace(); + } + + return null; + + } + + public static Object[] getZipFileNamesFromFolder(String filepath) { + return filterFileNamesFromFolder(filepath, ".zip"); + } + + public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){ + int fileCounter = 0; + for (String artifact : artifactsArr){ + String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length()); + if (extensionFile.equals(reqExtension)){ + fileCounter++; + } + } + return fileCounter; + } + + + public static synchronized File getLastModifiedFileFromDir() throws Exception{ + return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory()); + } + + public static synchronized File getLastModifiedFileFromDir(String dirPath){ + File dir = new File(dirPath); + File[] files = dir.listFiles(); + if (files == null) { + assertTrue("File not found under directory " + dirPath, false); + return null; + } + + File lastModifiedFile = files[0]; + for (int i = 1; i < files.length; i++) { + if(files[i].isDirectory()) { + continue; + } + if (lastModifiedFile.lastModified() < files[i].lastModified()) { + lastModifiedFile = files[i]; + } + } + return lastModifiedFile; + } + + public static void deleteDirectory(String directoryPath) { + File dir = new File(directoryPath); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to delete " + dir); + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir); + } + } + + public static void createDirectory(String directoryPath) { + File directory = new File(String.valueOf(directoryPath)); + if (! directory.exists()){ + directory.mkdir(); + } + } + + + /** + * The method append data to existing file, if file not exists - create it + * @param pathToFile + * @param text + * @param leftSpaceCount + * @throws IOException + */ + public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + try { + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + bw.write(sb.toString() + text); + bw.newLine(); + bw.close(); + fw.close(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + try { + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + for(Map.Entry<String, Pair<String, Object>> entry : dataMap.entrySet()){ + Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right); + bw.write(sb.toString() + record); + bw.newLine(); + } + bw.close(); + fw.close(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static void deleteLastDowloadedFiles(List<File> files) throws IOException { + for (File file : files) { + File fileToDelete =new File(Config.instance().getWindowsDownloadDirectory()+file.getName()); + fileToDelete.delete(); + } + } + + public static void cleanCurrentDownloadDir() throws IOException { + try{ + ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory()); + System.gc(); + FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory())); + } + catch(Exception e){ + + } + } + + public static boolean isFileDownloaded(String downloadPath, String fileName) { + boolean flag = false; + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + for (int i = 0; i < dir_contents.length; i++) { + if (dir_contents[i].getName().equals(fileName)) + return flag = true; + } + return flag; + } + + public static String getMD5OfFile(File file) throws IOException { + String content = FileUtils.readFileToString(file); + String md5 = GeneralUtility.calculateMD5ByString(content); + return md5; + } + + public static File createEmptyFile(String fileToCreate) { + File file= new File(fileToCreate); + try { + if(file.exists()){ + deleteFile(file); + } + file.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return file; + } + + public static File createEmptyFile(File fileToCreate) { + try { + if(fileToCreate.exists()){ + deleteFile(fileToCreate); + } + fileToCreate.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return fileToCreate; + } + + public static void deleteFile(File file){ + + try{ + if(file.exists()){ + file.deleteOnExit(); + SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted"); + }else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName()); + } + }catch(Exception e){ + e.printStackTrace(); + } + + } + + + /** + * get file list from directory by extension array + * @param directory + * @param okFileExtensions + * @return + */ + public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){ + + List<File> fileList = new ArrayList<>(); + File[] files = directory.listFiles(); + + for (String extension : okFileExtensions){ + for(File file : files){ + if (file.getName().toLowerCase().endsWith(extension)){ + fileList.add(file); + } + } + } + return fileList; + } + + private static final int BUFFER_SIZE = 4096; + public static void unzip(String zipFilePath, String destDirectory) throws IOException { + File destDir = new File(destDirectory); + if (!destDir.exists()) { + destDir.mkdir(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); +// iterates over entries in the zip file + while (entry != null) { + String entryName; + if(System.getProperty("os.name").contains("Windows")){ + entryName = entry.getName().replaceAll("/", "\\"+File.separator); + }else{ + entryName = entry.getName(); + } + String filePath = destDirectory + entryName; + String currPath = destDirectory; + String[] dirs = entryName.split("\\"+File.separator); + String currToken; + for(int i = 0; i<dirs.length;++i){ + currToken = dirs[i]; + if(!entry.isDirectory() && i==dirs.length-1){ + extractFile(zipIn, filePath); + } else { + if(currPath.endsWith(File.separator)){ + currPath = currPath + currToken; + }else{ + currPath = currPath + File.separator + currToken; + } +// if the entry is a directory, make the directory + File dir = new File(currPath); + dir.mkdir(); + } + } + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } + + private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + } + + public static int getFileCountFromDefaulDownloadDirectory(){ + return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length; + } + + + public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) { + Properties prop = new Properties(); + InputStream input = null; + String value = null; + try { + input = new FileInputStream(fullPath); + prop.load(input); + value = (prop.getProperty(key)); + + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return value.replaceAll("\"",""); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java new file mode 100644 index 0000000000..19c2242550 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java @@ -0,0 +1,790 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.awt.AWTException; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.ci.tests.datatypes.CatalogFilterTitlesEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.DashboardCardEnum; +import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.Keys; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedCondition; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.FluentWait; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + + +public final class GeneralUIUtils { + + public static final String FILE_NAME = "Valid_tosca_Mycompute.yml"; + + private static int timeOut=(int) (60*1.5); + +// public static void setTimeOut(int time) { +// if (time>0) { +// timeOut=time; +// } +// else { +// timeOut=timeOut; +// } +// } + + /**************** DRIVER ****************/ + + public static WebDriver getDriver() { + try{ + return DriverFactory.getDriver(); + } + catch(Exception e){ + e.printStackTrace(); + } + return null; + } + /****************************************/ + + public static List<WebElement> getElemenetsFromTable(By by) { + return getDriver().findElements(by); + } + + public static File takeScreenshot(String screenshotFilename, String dir, String testName) throws IOException { + if (screenshotFilename == null) { + if (testName != null){ + screenshotFilename = testName; + } + else + { + screenshotFilename = UUID.randomUUID().toString(); + } + } + try { + File scrFile = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE); + File filePath = new File(String.format("%s/%s.png", dir, screenshotFilename)); + new File(dir).mkdirs(); + FileUtils.copyFile(scrFile, filePath); + return filePath; + } catch (IOException e1) { + e1.printStackTrace(); + } + return null; + } + + public static File takeScreenshot(String screenshotFilename, String dir) throws IOException{ + return takeScreenshot(screenshotFilename, dir, null); + } + + + public static void scrollDown() { + try{ + Robot robot = new Robot(); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + GeneralUIUtils.waitForLoader(); + } + catch(Exception e){ + e.printStackTrace(); + } + } + + public static void minimizeCatalogFilterByTitle(CatalogFilterTitlesEnum titlesEnum) { + + switch (titlesEnum) { + case CATEGORIES: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + case STATUS: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + case TYPE: + GeneralUIUtils.getWebElementByTestID(titlesEnum.getValue()).click(); + break; + default: + break; + } + + } + + public static WebElement getWebElementByTestID(String dataTestId) { + return getWebElementByTestID(dataTestId, timeOut); + } + + public static WebElement getWebElementByTestID(String dataTestId, int timeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static boolean isWebElementExistByTestId(String dataTestId) { + if(getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).size() == 0) { + return false; + } + return true; + } + + public static WebElement getInputElement(String dataTestId) { + try{ + ultimateWait(); + return getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static List<WebElement> getInputElements(String dataTestId) { + ultimateWait(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + + } + + public static WebElement getWebElementBy(By by) { + return getWebElementBy(by, timeOut); + } + + public static WebElement getWebElementBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(by)); + } + + public static List<String> getWebElementListText(List<WebElement>elements) { + List<String>Text=new ArrayList<>(); + for (WebElement webElement : elements) { + Text.add(webElement.getText()); + } + return Text; + } + + + public static List<WebElement> getWebElementsListBy(By by) { + return getWebElementsListBy(by, timeOut); + } + + public static List<WebElement> getWebElementsListBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); + } + + public static List<WebElement> getWebElementsListByContainTestID(String dataTestId) { + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), 10); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@data-tests-id, '"+dataTestId+"')]"))); + } + catch(Exception e){ + return new ArrayList<WebElement>(); + } + } + + public static List<WebElement> getWebElementsListByContainsClassName(String containedText) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@class, '"+containedText+"')]"))); + } + + public static WebElement getWebElementByContainsClassName(String containedText) { + return getWebElementBy(By.xpath("//*[contains(@class, '"+containedText+"')]")); + } + + public static WebElement getWebElementByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className))); + } + + public static WebElement getWebElementByLinkText(String linkText) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@text='" + linkText + "']"))); + } + + + public static List<WebElement> getWebElementsListByTestID(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static List<WebElement> getWebElementsListByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className(className))); + } + + + + + public static Boolean isElementInvisibleByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until( + ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean isElementVisibleByTestId(String dataTestId) { + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + if(wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//*[@data-tests-id='" + dataTestId + "']")))).isDisplayed()){ + return true; + }else { + return false; + } + } + catch(Exception e){ + return false; + } + } + + public static void clickOnElementByTestId(String dataTestId) { + clickOnElementByTestIdWithoutWait(dataTestId); + ultimateWait(); + } + + public static void clickOnElementByTestIdWithoutWait(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static void clickOnElementByTestId(String dataTestId, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static WebElement waitForElementVisibilityByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId) { + return waitForElementInVisibilityByTestId(dataTestId, timeOut); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "'])"))); + ultimateWait(); + return until; + } + return false; + } + + public static Boolean waitForElementInVisibilityByTestId(By by) { + return waitForElementInVisibilityBy(by, timeOut); + } + + + public static Boolean waitForElementInVisibilityBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(by).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(by)); + sleep(1000); + return until; + } + return false; + } + + + public static void setWebElementByTestId(String elemetID, String value) { + WebElement resourceDescriptionTextbox = GeneralUIUtils.getWebElementByTestID(elemetID); + resourceDescriptionTextbox.clear(); + resourceDescriptionTextbox.sendKeys(value); + + } + + public static WebElement hoverOnAreaByTestId(String areaId) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByTestID(areaId); + actions.moveToElement(area).perform(); + ultimateWait(); + return area; + } + + public static WebElement hoverOnAreaByClassName(String className) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByClassName(className); + actions.moveToElement(area).perform(); + GeneralUIUtils.ultimateWait(); + return area; + } + + public static void clickElementUsingActions(WebElement element){ + Actions actions = new Actions(getDriver()); + + actions.moveToElement(element); + actions.perform(); + + actions.click(); + actions.perform(); + + ultimateWait(); + } + + public static void waitForLoader() { + waitForLoader(timeOut); + } + + public static void waitForLoader(int timeOut) { + sleep(500); + waitForElementInVisibilityBy(By.className("tlv-loader"), timeOut); + } + + public static void findComponentAndClick(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in homepage"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + try{ + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't interact with search bar"); + e.printStackTrace(); + } + + + try{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component from home screen", resourceName)); + clickOnElementByTestId(resourceName); + GeneralUIUtils.ultimateWait(); + getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on component named " + resourceName); + e.printStackTrace(); + } + } + + + public static String getComponentVersion(String componentName) { + return GeneralUIUtils.getWebElementByTestID(componentName + "Version").getText(); + } + + public static void windowZoomOut() { + final int zoomOutFactor = 3; + for (int i = 0; i < zoomOutFactor; i++) { + if(getDriver() instanceof FirefoxDriver) { + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT)); + } + } + } + + public static void resetZoom(){ + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0")); + } + + public static void windowZoomOutUltimate(){ + resetZoom(); + windowZoomOut(); +// JavascriptExecutor js = (JavascriptExecutor) driver; +// js.executeScript("document.body.style.zoom='90%'"); + } + + public static void clickASDCLogo() { + WebDriverWait wait = new WebDriverWait(getDriver(), 15); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("ASDC"))); + WebElement ClickASDCLogo = getDriver().findElement(By.linkText("ASDC")); + ClickASDCLogo.click(); + GeneralUIUtils.waitForLoader(); + } + + public static void sleep(int duration) { + try { + Thread.sleep(duration); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public static void moveToStep(DataTestIdEnum.StepsEnum Stepname) { + moveToStep(Stepname.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to %s page ", Stepname.toString())); + } + + public static void moveToStep(String dataTestId) { + clickOnElementByTestId(dataTestId); + ultimateWait(); + } + + + public static Select getSelectList(String item, String datatestsid) { + Select selectlist = new Select(getWebElementByTestID(datatestsid)); + if (item != null) { + selectlist.selectByVisibleText(item); + } + return selectlist; + } + + public static List<WebElement> waitForElementsListVisibilityTestMethod(DashboardCardEnum dataTestId) { + GeneralUIUtils.waitForLoader(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']")); + } + + public static List<WebElement> getElementsByCSS(String cssString) throws InterruptedException { + GeneralUIUtils.waitForLoader(); + List<WebElement> assets = getDriver().findElements(By.cssSelector(cssString)); + return assets; + } + + public static WebElement getElementfromElementByCSS(WebElement parentElement, String cssString){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + GeneralUIUtils.waitForLoader(); + return parentElement.findElement(By.cssSelector(cssString)); + } + + public static WebElement getElementfromElementByXPATH(WebElement parentElement, DashboardCardEnum dataTestId){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + GeneralUIUtils.waitForLoader(); + return HighlightMyElement( parentElement.findElement(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']"))); + } + + public static WebElement HighlightMyElement(WebElement element) { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + javascript.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 4px solid yellow;"); + return element; + } + + public static WebElement getSelectedElementFromDropDown(String dataTestId){ + GeneralUIUtils.ultimateWait();; + WebElement selectedElement = new Select (getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).getFirstSelectedOption(); + return selectedElement; + } + + + public static void waitForPageLoadByReadyState() { + new WebDriverWait(getDriver(), 30).until((ExpectedCondition<Boolean>) wd -> + ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); + } + + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier<List<WebElement>> func) { + int maxWaitingPeriodMS = 10 * 1000; + int napPeriodMS = 100; + int sumOfWaiting = 0; + List<WebElement> elements = null; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + elements = func.get(); + isKeepWaiting = (expectedElementsCount == elements.size()); + sleep(napPeriodMS); + sumOfWaiting += napPeriodMS; + if (sumOfWaiting > maxWaitingPeriodMS) + return false; + } + return true; + } + + public static String getActionDuration(Runnable func) throws Exception{ + long startTime = System.nanoTime(); + func.run(); + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + String durationString = String.format("%02d:%02d", duration / 60, duration % 60); + return durationString; + } + + public static WebElement clickOnAreaJS(String areaId) { + return clickOnAreaJS(areaId, timeOut); + } + + + public static WebElement clickOnAreaJS(String areaId, int timeout) { + try{ + ultimateWait(); + WebElement area = getWebElementByTestID(areaId); + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + Object executeScript = javascript.executeScript("arguments[0].click();", area, "color: yellow; border: 4px solid yellow;"); + waitForLoader(timeout); + return area; + } + catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + + + public static WebElement clickOnAreaJS(WebElement areaId) throws InterruptedException { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + javascript.executeScript("arguments[0].click();", areaId, "color: yellow; border: 4px solid yellow;"); + return areaId; + } + + + + public static void clickSomewhereOnPage() { + getDriver().findElement(By.cssSelector(".asdc-app-title")).click(); + } + + public static void findComponentAndClickInCatalog(String resourceName) throws Exception { + // This method will find element by element name, don't use data-tests-id argument + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + clickOnElementByText(resourceName); + ultimateWait(); + } + + public static void clickOnElementByText(String textInElement) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + HighlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickOnElementByText(String textInElement, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + HighlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickJSOnElementByText(String textInElement) throws Exception { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + clickOnAreaJS(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))); + } + + public static void fluentWaitTestID(String dataTestId, String text) { + FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(getDriver()) + .withTimeout(30, TimeUnit.SECONDS) + .pollingEvery(50, TimeUnit.MILLISECONDS) + .ignoring(NoSuchElementException.class); + + fluentWait.until(ExpectedConditions.refreshed( + ExpectedConditions.textToBePresentInElementValue(By.xpath("//*[@data-tests-id='" + dataTestId + "']"), text))); + } + + public static void regularWait(WebElement element, String text){ + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + + wait.until(ExpectedConditions.textToBePresentInElementValue(element, text)); + } + + public static void waitForAngular(){ + WebDriverWait wait = new WebDriverWait(getDriver(), 90, 100); + wait.until(AdditionalConditions.pageLoadWait()); + wait.until(AdditionalConditions.angularHasFinishedProcessing()); + } + + public static Object getAllElementAttributes(WebElement element) { + return ((JavascriptExecutor)getDriver()).executeScript("var s = []; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; s.push(a.name + ':' + a.value); } ; return s;", element); + } + + public static boolean isElementReadOnly(WebElement element){ + try { + HighlightMyElement(element).clear(); + return false; + } catch (Exception e) { + return true; + } + } + + public static boolean isElementReadOnly(String dataTestId){ + return isElementReadOnly( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static boolean isElementDisabled(WebElement element){ + return HighlightMyElement(element).getAttribute("class").contains("view-mode") || + element.getAttribute("class").contains("disabled"); + } + + public static boolean isElementDisabled(String dataTestId){ + return isElementDisabled( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static void ultimateWait(){ + long startTime = System.nanoTime(); + + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForBackLoader(); + GeneralUIUtils.waitForAngular(); + + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); +// System.out.println("UltimateWait took: "+ duration); + if(duration > timeOut){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Delays on page, %d seconds", duration)); + } +// waitForUINotification(); + } + + public static WebElement makeElementVisibleWithJS(WebElement element){ + String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement unhideElement(WebElement element, String attributeValue){ + String js = "arguments[0].setAttribute('class','" + attributeValue + "');"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement findByText(String textInElement){ + return getDriver().findElement(searchByTextContaining(textInElement)); + } + public static By searchByTextContaining(String textInElement) { + return By.xpath("//*[contains(text(),'" + textInElement + "')]"); + } + + + public static boolean findAndWaitByText(String textInElement, int timeout){ + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + wait.until(ExpectedConditions.presenceOfElementLocated(searchByTextContaining(textInElement))); + return true; + } + catch(Exception e){ + return false; + } + } + + public static WebElement getClickableButtonBy(By by, int timout){ + try{ + WebDriverWait wait = new WebDriverWait(getDriver(), timout); + WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); + return element; + } + catch(Exception e){ + return null; + } + } + + + + public static WebElement getButtonWithText(String textInButton){ + try{ + return getDriver().findElement(By.xpath("//button[contains(text(),'" + textInButton + "')]")); + } + catch(Exception e) + { + return null; + } + } + + + public static List<WebElement> getElementsByDataTestsIdStartWith(String startWithString){ + ultimateWait(); + return getDriver().findElements(By.xpath("//*[starts-with(@data-tests-id,'" + startWithString + "')]")); + } + + public static void closeErrorMessage() { + WebElement okWebElement = getButtonWithText("OK"); + if (okWebElement != null){ + okWebElement.click(); + ultimateWait(); + } + } + + public static WebElement getElementByCSS(String cssString) throws InterruptedException { + ultimateWait(); + return getDriver().findElement(By.cssSelector(cssString)); + } + + public static String getDataTestIdAttributeValue(WebElement element) { + return element.getAttribute("data-tests-id"); + } + + public static String getTextContentAttributeValue(WebElement element) { + return element.getAttribute("textContent"); + } + + public static WebElement getElementInsideElementByDataTestsId(WebElement element, String dataTestId) { + try{ + return element.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static void clickOnElementByCSS(String cssString) throws Exception { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssString))).click(); + ultimateWait(); + } + public static String getRandomComponentName(String prefix) { + return prefix + GeneralUIUtils.randomNumber(); + } + public static int randomNumber() { + Random r = new Random(); + return r.nextInt(10000); + } + + public static void waitForUINotification() { + List<WebElement> notificationElements = getDriver().findElements(By.className("ui-notification")); + if (!notificationElements.isEmpty()){ + notificationElements.forEach(WebElement::click); + } + } + + public static boolean checkForDisabledAttribute(String dataTestId){ + Object elementAttributes = getAllElementAttributes(waitForElementVisibilityByTestId(dataTestId)); + return elementAttributes.toString().contains("disabled"); + } + + public static void dragAndDropElementByY(WebElement area, int yOffset) { + Actions actions = new Actions(getDriver()); + actions.dragAndDropBy(area, 10, yOffset).perform(); + ultimateWait(); + } + + public static void waitForBackLoader() { + waitForBackLoader(timeOut); + } + + public static void waitForBackLoader(int timeOut) { + sleep(100); + waitForElementInVisibilityBy(By.className("tlv-loader-back"), timeOut); + } + + public static void addStringtoClipboard(String text){ + StringSelection selection = new StringSelection(text); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(selection, selection); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java new file mode 100644 index 0000000000..1bef2ad32c --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import org.openecomp.sdc.ci.tests.datatypes.TopMenuButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class HomeUtils { + + public static WebElement createAndImportButtons(CreateAndImportButtonsEnum type, WebDriver driver) + throws InterruptedException { + switch (type) { + case IMPORT_CP: + case IMPORT_VFC: + case IMPORT_VL: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue()); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.IMPORT_VFC.getValue()); + + case IMPORT_VF: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue()); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.IMPORT_VFC.getValue()); + case CREATE_SERVICE: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + ; + break; + + case CREATE_PRODUCT: + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + break; + + default: + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + driver.findElement(By.xpath("//*[@data-tests-id='createResourceButton']")).click(); + break; + } + return null; + + } + + public static String checkBoxLifeCyclestate(CheckBoxStatusEnum lifeCycle) { + String Status = "IN DESIGN CHECK OUT"; + switch (lifeCycle) { + case CHECKIN: + Status = "IN DESIGN CHECK IN"; + if (GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).isDisplayed()) { + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + } + break; + case CHECKOUT: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "IN DESIGN CHECK OUT"; + break; + case IN_TESTING: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "IN TESTING"; + break; + case READY_FOR_TESTING: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "READY FOR TESTING"; + break; + case CERTIFIED: + GeneralUIUtils.getWebElementByTestID(lifeCycle.getValue()).click(); + Status = "CERTIFIED"; + break; + } + return Status; + } + + public static void findComponentAndClick(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "finding component " + componentName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName); + WebElement foundComp = null; + try { + foundComp = GeneralUIUtils.getWebElementByTestID(componentName); + foundComp.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (Exception e) { + String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName); + SetupCDTest.getExtendTest().log(Status.FAIL, msg); + System.out.println(msg); + Assert.fail(msg); + } + } + + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java new file mode 100644 index 0000000000..d1045eab76 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; + +public class ImportAssetUIUtils { + + public static final String FILE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\Files\\"; + public static String fileName = "JDM_vfc.yml"; + public static final String toscaErrorMessage = "Invalid TOSCA template."; + public static final String yamlError = "Invalid YAML file."; + public static final String allReadyExistErro = "Imported resource already exists in ASDC Catalog."; + + public static void importAsssetAndFillGeneralInfo(String FILE_PATH, String fileName, + ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception { + ResourceUIUtils.importFileWithSendKey(FILE_PATH, fileName, type); + ResourceUIUtils.fillResourceGeneralInformationPage(resourceDetails, user,true); + } + + public static void importAsssetFillGeneralInfoAndSelectIcon(String FILE_PATH, String fileName, + ResourceReqDetails resourceDetails, User user, CreateAndImportButtonsEnum type) throws Exception { + importAsssetAndFillGeneralInfo(FILE_PATH, fileName, resourceDetails, user, type); + GeneralPageElements.clickCreateButton(); + ResourceUIUtils.selectRandomResourceIcon(); + } + + // checking or unchecking the checkbox on right palette at designer + // workspace + public static void checkbox(String checkBoxname, WebDriver driver) { + driver.findElement(By.xpath("//label[@for='" + checkBoxname + "']")).click(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java new file mode 100644 index 0000000000..dfb4b74fac --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java @@ -0,0 +1,801 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; +import org.openecomp.sdc.ci.tests.execute.setup.ArtifactsCorrelationManager; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.HomePage; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.verificator.VfVerificator; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +public class OnboardingUtils { + + public OnboardingUtils() { + } + + private static String vendorId; + private static String vendorLicenseName; + private static String vendorLicenseAgreementId; + private static String featureGroupId; + + public static Pair<String, Map<String, String>> createVendorSoftwareProduct(String HeatFileName, String filepath, User user) + throws Exception { + Pair<String, Map<String, String>> pair = createVSP(HeatFileName, filepath, user); + + String vspid = pair.right.get("vspId"); + + prepareVspForUse(user, vspid); + + return pair; + } + + public static void prepareVspForUse(User user, String vspid) throws Exception { + RestResponse checkin = checkinVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue()); + + RestResponse submit = submitVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product"); + } + + public static Pair<String, Map<String, String>> createVSP(String HeatFileName, String filepath, User user) throws Exception { + String vspName = handleFilename(HeatFileName); + + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product"); + + Pair<RestResponse, Map<String, String>> createNewVspPair = createNewVendorSoftwareProduct(vspName, vendorLicenseName, vendorId, vendorLicenseAgreementId, featureGroupId, user); + RestResponse createNewVendorSoftwareProduct = createNewVspPair.left; + assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue()); + String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId"); + String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId"); + + Map<String, String> vspMeta = createNewVspPair.right; + Map<String, String> vspObject = new HashMap<String, String>(); + Iterator<String> iterator = vspMeta.keySet().iterator(); + while(iterator.hasNext()){ + Object key = iterator.next(); + Object value = vspMeta.get(key); + vspObject.put(key.toString(), value.toString()); + } + vspObject.put("vspId", vspid); + vspObject.put("componentId", componentId); + vspObject.put("vendorName", vendorLicenseName); + vspObject.put("attContact", user.getUserId()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspid, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject); + + return pair; + } + + public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user) throws Exception{ + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_POLL); + ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_TRAP); + addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId); + prepareVspForUse(user, vspId); + } + + public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user) + throws Exception, Throwable { + String vspName = handleFilename(HeatFileName); + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product"); + + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspId, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspId, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + RestResponse checkin = checkinVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); + + + RestResponse submit = submitVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product"); + + return vspName; + } + + public static String handleFilename(String heatFileName) { + final String namePrefix = "ciVFOnboarded-"; + final String nameSuffix = "-" + getShortUUID(); + + String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf(".")); + + if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) { + subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length()); + } + + if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) { + subHeatFileName = subHeatFileName.replace("(", "-"); + subHeatFileName = subHeatFileName.replace(")", "-"); + } + + String vnfName = namePrefix + subHeatFileName + nameSuffix; + return vnfName; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user, String vspComponentId) throws Exception{ + vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId; + if (vspComponentId != null){ + if (snmpPoll != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll); + RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue()); + } + if (snmpTrap != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap); + RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue()); + } + } + + return vspComponentId; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user) throws Exception{ + return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vspid, user, null); + } + + private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpPollUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpPollUrl, user); + } + + private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpTrapUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp-trap/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpTrapUrl, user); + } + + private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s", + config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); + String userId = user.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendDelete(url, headersMap); + return response; + } + + + + private static String getVSPComponentId(String vspid, User user) throws Exception, JSONException { + RestResponse components = getVSPComponents(vspid, user); + String response = components.getResponse(); + Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response); + JSONArray results = (JSONArray)responseMap.get("results"); + for (Object res : results){ + Map<String, Object> compMap= (Map<String, Object>) JSONValue.parse(res.toString()); + String componentId = compMap.get("id").toString(); + return componentId; + } + return null; + } + + private static RestResponse getVSPComponents(String vspid, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components", config.getCatalogBeHost(),config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + public static void createVendorLicense(User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license"); + vendorLicenseName = "ciLicense" + getShortUUID(); + RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user); + assertEquals("did not succeed to create vendor license model", 200, + vendorLicenseResponse.getErrorCode().intValue()); + vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value"); + + RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user); + assertEquals("did not succeed to create vendor key groups", 200, + vendorKeyGroupsResponse.getErrorCode().intValue()); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); + + RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user); + assertEquals("did not succeed to create vendor entitlement pool", 200, + vendorEntitlementPool.getErrorCode().intValue()); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), + "value"); + + RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, + entitlementPoolId, user); + assertEquals("did not succeed to create vendor license feature groups", 200, + vendorLicenseFeatureGroups.getErrorCode().intValue()); + featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); + + RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user); + assertEquals("did not succeed to create vendor license agreement", 200, + vendorLicenseAgreement.getErrorCode().intValue()); + vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), + "value"); + + RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user); + assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); + + RestResponse submitVendorLicense = submitVendorLicense(vendorId, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + + SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license"); + } + + private static String getShortUUID() { + return UUID.randomUUID().toString().split("-")[0]; + } + + private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/versions/0.1/actions", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("action", action); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap); + return response; + } + + public static RestResponse checkinVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-license-models", user); + } + + public static RestResponse submitVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-license-models", user); + } + + public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), + config.getCatalogBePort()); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("vendorName", name); + jObject.put("description", "new vendor license model"); + jObject.put("iconRef", "icon"); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-agreements", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject licenseTermpObject = new JSONObject(); + licenseTermpObject.put("choice", "Fixed_Term"); + licenseTermpObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "abc"); + jObjectBody.put("description", "new vendor license agreement"); + jObjectBody.put("requirementsAndConstrains", "abc"); + jObjectBody.put("licenseTerm", licenseTermpObject); + jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId, + String entitlementPoolId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/feature-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("name", "xyz"); + jObject.put("description", "new vendor license feature groups"); + jObject.put("partNumber", "123abc456"); + jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); + jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/entitlement-pools", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jEntitlementMetricObject = new JSONObject(); + jEntitlementMetricObject.put("choice", "CPU"); + jEntitlementMetricObject.put("other", ""); + + JSONObject jAggregationFunctionObject = new JSONObject(); + jAggregationFunctionObject.put("choice", "Peak"); + jAggregationFunctionObject.put("other", ""); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jTimeObject = new JSONObject(); + jTimeObject.put("choice", "Hour"); + jTimeObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "def"); + jObjectBody.put("description", "new vendor license entitlement pool"); + jObjectBody.put("thresholdValue", "23"); + jObjectBody.put("thresholdUnits", "Absolute"); + jObjectBody.put("entitlementMetric", jEntitlementMetricObject); + jObjectBody.put("increments", "abcd"); + jObjectBody.put("aggregationFunction", jAggregationFunctionObject); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("time", jTimeObject); + jObjectBody.put("manufacturerReferenceNumber", "123aaa"); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-key-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "keyGroup"); + jObjectBody.put("description", "new vendor license key group"); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("type", "Universal"); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static Pair<RestResponse, Map<String, String>> createNewVendorSoftwareProduct(String name, String vendorName, String vendorId, + String licenseAgreementId, String featureGroupsId, User user) throws Exception { + + Map<String, String> vspMetadta = new HashMap<String, String>(); + + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products", + config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = user.getUserId(); + + JSONObject jlicensingDataObj = new JSONObject(); + jlicensingDataObj.put("licenseAgreement", licenseAgreementId); + jlicensingDataObj.put("featureGroups", Arrays.asList(featureGroupsId).toArray()); + + JSONObject jlicensingVersionObj = new JSONObject(); + jlicensingVersionObj.put("id", "1.0"); + jlicensingVersionObj.put("label", "1.0"); + + JSONObject jObject = new JSONObject(); + jObject.put("name", name); + jObject.put("description", "new VSP description"); + jObject.put("category", "resourceNewCategory.generic"); + jObject.put("subCategory", "resourceNewCategory.generic.database"); + jObject.put("licensingVersion", jlicensingVersionObj); + jObject.put("vendorName", vendorName); + jObject.put("vendorId", vendorId); + jObject.put("icon", "icon"); + jObject.put("licensingData", jlicensingDataObj); + + vspMetadta.put("description", jObject.getString("description")); + vspMetadta.put("category", jObject.getString("category")); + vspMetadta.put("subCategory", jObject.getString("subCategory").split("\\.")[2]); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + + return new Pair<RestResponse, Map<String, String>>(response, vspMetadta); + } + + public static RestResponse getVendorSoftwareProduct(Map vspObject, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/" + vspObject.get("vspId"), + config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = user.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpsSendGet(url, headersMap); + + return response; + } + + public static RestResponse validateUpload(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate/process", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + String userId = user.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + String body =null; + + RestResponse response = http.httpSendPut(url, body, headersMap); + + return response; + } + + public static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate", config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + return uploadFile(filepath, filename, url, user); + } + + private static RestResponse uploadFile(String filepath, String filename, String url, User user) + throws FileNotFoundException, IOException, ClientProtocolException { + CloseableHttpResponse response = null; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename))); + + Map<String, String> headersMap = prepareHeadersMap(user.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + + Iterator<String> iterator = headersMap.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = headersMap.get(key); + httpPost.addHeader(key, value); + } + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static File getTestZipFile(String filepath, String filename) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); + return filePath.toFile(); + } + + public static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-software-products", user); + } + + private static RestResponse checkoutVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkout", "vendor-software-products", user); + } + + public static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-software-products", user); + } + + public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user); + } + + protected static Map<String, String> prepareHeadersMap(String userId) { + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + return headersMap; + } + + + private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{ + String vspName = vsp.left; + Map<String, String> vspMetadata = vsp.right; + boolean vspFound = HomePage.searchForVSP(vspName); + + if (vspFound){ + + List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable(); +// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); +// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); +// findElement.click(); + elemenetsFromTable.get(1).click(); + GeneralUIUtils.waitForLoader(); + + if (isUpdate){ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + + } + else{ + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + } + + String lifeCycleState = ResourceGeneralPage.getLifeCycleState(); + boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue()); + if (needCheckout) + { + try { + ResourceGeneralPage.clickCheckoutButton(); + Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout"); + + } catch (Exception e) { + ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout"); + e.printStackTrace(); + } + GeneralUIUtils.waitForLoader(); + } + + //Metadata verification + VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata); + + ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); + String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated()); + ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); + } + else{ + Assert.fail("Did not find VSP named " + vspName); + } + } + + private static void waitUntilVnfCreated() { + GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(60*10); + GeneralUIUtils.waitForAngular(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{ + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); + importUpdateVSP(vsp, true); + } + + public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{ + ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); + importUpdateVSP(vsp, false); + } + + public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable { + ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); + System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile)); + + Map<String, String> vspMap = vsp.right; + String vspId = vspMap.get("vspId"); + + updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user); + HomePage.showVspRepository(); + updateVSP(vsp); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile); + } + + public static Pair<String, Map<String, String>> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); + System.out.println(String.format("Going to onboard the VNF %s", vnfFile)); + + createVendorLicense(user); + Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user); + String vspName = createVendorSoftwareProduct.left; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); + File latestFilefromDir = FileHandling.getLastModifiedFileFromDir(); + + ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); + importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); + ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); + + for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { + if(deploymentArtifact.getType().equals("HEAT_ENV")) { + continue; + } else if(deploymentArtifact.getFileName().contains(".")) { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")), "1", deploymentArtifact.getType()); + } else { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim(), "1", deploymentArtifact.getType()); + } + + } + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + return createVendorSoftwareProduct; + } + +} + +enum SnmpTypeEnum{ + SNMP_POLL ("snmp"), + SNMP_TRAP ("snmp-trap"); + + private String value; + + public String getValue() { + return value; + } + + private SnmpTypeEnum(String value) { + this.value = value; + } + + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java new file mode 100644 index 0000000000..9e478c8523 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ProductUIUtils.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.awt.AWTException; +import java.util.List; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ProductGeneralPage; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +/** + * @author al714h + * + */ + +public class ProductUIUtils { + + protected static WebDriver driver; + + public ProductUIUtils(TestName name, String className) { + super(); + } + + public static void fillProductGeneralPage(ProductReqDetails product, User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Fill in metadata values in general page.. ")); + ProductGeneralPage.defineName(product.getName()); + ProductGeneralPage.defineFullName(product.getFullName()); + ProductGeneralPage.defineDescription(product.getDescription()); + ProductGeneralPage.defineProjectCode(product.getProjectCode()); + defineTagsList2(product.getTags()); + ProductGeneralPage.defineContactId(product.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createProduct(ProductReqDetails product, User user) throws Exception, AWTException { + clikAddProduct(); + fillProductGeneralPage(product, user); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Product %s created", product.getName())); + } + + public static void defineTagsList2(List<String> productTags){ + WebElement productTagsTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.TAGS.getValue()); + for (String tag : productTags) { + productTagsTextbox.clear(); + productTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + productTagsTextbox.sendKeys(Keys.ENTER); + } + } + + public static void clikAddProduct(){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking Add Product button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Product button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java new file mode 100644 index 0000000000..62b2f832bd --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PropertiesUIUtils.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.PropertiesPage; +import org.openqa.selenium.WebElement; + +import com.aventstack.extentreports.Status; + +public class PropertiesUIUtils { + + // public static void addPropertByType(String type,String name,String + // defaultValue,String description) throws Exception{ + // + // ResourceUIUtils.defineNewSelectList(type); + // ResourceUIUtils.definePropertyName(name); + // ResourceUIUtils.defineDefaultValueByType(defaultValue); + // ResourceUIUtils.defineDescription(description); + // Thread.sleep(2000); + // ResourceUIUtils.clickButton("Add"); + // } + public static Map<String, String> addProperties(String name, String itemType, String defaultValue, + String description, String schemaType) throws Exception { + Map<String, String> propertyvalues = new HashMap<String, String>(); + GeneralUIUtils.getSelectList(itemType, "propertyType"); + ResourceUIUtils.definePropertyName(name); + if (itemType == "boolean") { + ResourceUIUtils.defineBoolenDefaultValue(defaultValue); + GeneralUIUtils.setWebElementByTestId("description","description"); + Thread.sleep(2000); + GeneralUIUtils.getWebElementByTestID("Add").click(); + ; + } else if (itemType == "list" || itemType == "map") { + GeneralUIUtils.getSelectList(schemaType, "schemaType"); + } + if (!(itemType == "boolean")) { + ResourceUIUtils.defineDefaultValueByType(defaultValue); + GeneralUIUtils.setWebElementByTestId("description", "des"); + GeneralUIUtils.getWebElementByTestID("Add").click(); + ; + Thread.sleep(2000); + } + propertyvalues.put("type", itemType); + propertyvalues.put("defaultValue", defaultValue); + propertyvalues.put("description", description); + propertyvalues.put("name", name); + + return propertyvalues; + } + + public static void vlidateProperties(Map<String, String> propertyValues) throws InterruptedException { + WebElement name = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + name.getText().equalsIgnoreCase(propertyValues.get("name")); + WebElement defaultValue = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + defaultValue.getText().equalsIgnoreCase(propertyValues.get("defaultValue")); + WebElement type = GeneralUIUtils.getWebElementByTestID(propertyValues.get("type")); + type.getText().equalsIgnoreCase(propertyValues.get("type")); + } + + public static void addNewProperty(PropertyTypeEnum property) { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding new %s property", property.name())); + PropertiesPage.clickAddPropertyArtifact(); + PropertiesPage.getPropertyPopup().insertPropertyName(property.getName()); + PropertiesPage.getPropertyPopup().selectPropertyType(property.getType()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void updateProperty(PropertyTypeEnum property) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating property: %s", property.name())); + PropertiesPage.clickOnProperty(property.getName()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void changePropertyDefaultValueInComposition(String propertyName, String defaultValue) { + GeneralUIUtils.clickOnElementByTestId(propertyName); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(defaultValue); + PropertiesPage.getPropertyPopup().clickSave(); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java new file mode 100644 index 0000000000..c76bf4b74a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ResourceUIUtils.java @@ -0,0 +1,1143 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; +import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.Dashboard; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceCategoriesNameEnum; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.By; +import org.openqa.selenium.ElementNotVisibleException; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.AssertJUnit; + +import com.aventstack.extentreports.Status; + +public final class ResourceUIUtils { + public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-"; + protected static final boolean IS_BEFORE_TEST = true; + public static final String INITIAL_VERSION = "0.1"; + public static final String ICON_RESOURCE_NAME = "call_controll"; + protected static final String UPDATED_RESOURCE_ICON_NAME = "objectStorage"; + + private ResourceUIUtils() { + } + + static WebDriver driver = GeneralUIUtils.getDriver(); + + public static void defineResourceName(String resourceName) { + + WebElement resourceNameTextbox = GeneralUIUtils.getDriver().findElement(By.name("componentName")); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(resourceName); + } + + public static void defineResourceCategory(String category, String datatestsid) { + + GeneralUIUtils.getSelectList(category, datatestsid); + } + + // public static void uploadFileWithJavaRobot(String FilePath,String + // FileName) throws Exception{ + // + // StringSelection Path= new StringSelection(FilePath+FileName); + // Thread.sleep(1000); + // java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(Path, + // null); + // Robot robot = new Robot(); + // robot.delay(1000); + // robot.keyPress(KeyEvent.VK_CONTROL); + // robot.keyPress(KeyEvent.VK_V); + // robot.keyRelease(KeyEvent.VK_V); + // robot.keyRelease(KeyEvent.VK_CONTROL); + // robot.delay(1000); + // robot.keyPress(KeyEvent.VK_ENTER); + // robot.keyRelease(KeyEvent.VK_ENTER); + // robot.delay(1000); + // } + // click and upload tosca file //**to be changed. + public static void importFileWithSendKey(String FilePath, String FileName, CreateAndImportButtonsEnum type) + throws Exception { + WebElement importButton = HomeUtils.createAndImportButtons(type, driver).findElement(By.tagName("input")); + importButton.sendKeys(FilePath + FileName); + } + + public static void importFileWithSendKeyBrowse(String FilePath, String FileName) throws Exception { + WebElement browsebutton = GeneralUIUtils.getWebElementByTestID("browseButton"); + browsebutton.sendKeys(FilePath + FileName); + } + + // public static void defineVendorName(String resourceVendorName) { + // + // WebElement resourceVendorNameTextbox = + // GeneralUIUtils.getWebElementByTestID("vendorName"); + // resourceVendorNameTextbox.clear(); + // resourceVendorNameTextbox.sendKeys(resourceVendorName); + // } + + // public static void defineTagsList(ResourceReqDetails resource,String + // []resourceTags) { + // List<String>taglist = new ArrayList<String>();; + // WebElement resourceTagsTextbox = + // GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); + // for (String tag : resourceTags) { + // resourceTagsTextbox.clear(); + // resourceTagsTextbox.sendKeys(tag); + // resourceTagsTextbox.sendKeys(Keys.ENTER); + // taglist.add(tag); + // } + // resource.setTags(taglist); + // } + + public static String defineUserId(String userId) { + // + WebElement resourceUserIdTextbox = ResourceGeneralPage.getContactIdField(); + resourceUserIdTextbox.clear(); + resourceUserIdTextbox.sendKeys(userId); + return userId; + } + + public static void defineVendorRelease(String resourceVendorRelease) { + + WebElement resourceVendorReleaseTextbox = GeneralUIUtils.getWebElementByTestID("vendorRelease"); + resourceVendorReleaseTextbox.clear(); + resourceVendorReleaseTextbox.sendKeys(resourceVendorRelease); + } + + public static void selectResourceIcon(String resourceIcon) throws Exception { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@data-tests-id='" + resourceIcon + "']"))) + .click(); + } + + public static String definePropertyName(String name) { + + WebElement nameProperty = GeneralUIUtils.getDriver().findElement(By.name("propertyName")); + nameProperty.sendKeys(name); + return name; + } + + public static void selectRandomResourceIcon() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 4); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"))); + List<WebElement> iconElement = GeneralUIUtils.getDriver() + .findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")); + iconElement.get(0).click(); + } + + public static List<WebElement> getAllObjectsOnWorkspace(WebDriver driver, ResourceReqDetails resource) + throws Exception { + + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 10); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + resource.getName() + "']"))); + return GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@class='" + "w-sdc-dashboard-card-info-name" + "']")); + + } + + public static String getErrorMessageText(String text) throws Exception { + + return GeneralUIUtils.getWebElementByClassName(text).getText(); + + } + + public static WebElement scrollElement(WebDriver driver) throws Exception { + + return GeneralUIUtils.getDriver().findElement(By.className("ps-scrollbar-y")); + } + + public static void scrollDownPage() throws AWTException, InterruptedException { + Robot robot = new Robot(); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + robot.keyPress(KeyEvent.VK_PAGE_DOWN); + robot.keyRelease(KeyEvent.VK_PAGE_DOWN); + } + + public static void defineNewSelectList(String Text) { + WebElement mySelectElm = GeneralUIUtils.getDriver().findElement(By.className("i-sdc-form-select")); + Select mySelectString = new Select(mySelectElm); + mySelectString.selectByVisibleText(Text); + } + + public static void defineDefaultValueByType(String Value) { + + WebElement valueString = GeneralUIUtils.getDriver().findElement(By.name("value")); + valueString.clear(); + valueString.sendKeys(Value); + } + + public static void defineBoolenDefaultValue(String Value) { + + WebElement elementBoolean = GeneralUIUtils.getDriver().findElement(By.name("value")); + Select se = new Select(elementBoolean); + se.selectByValue(Value); + } + + public static void clickButtonBlue() { + WebElement clickButtonBlue = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue")); + clickButtonBlue.click(); + } + + public static void clickButton(String selectButton) { + + WebElement clickButton = GeneralUIUtils.getDriver() + .findElement(By.xpath("//*[@data-tests-id='" + selectButton + "']")); + clickButton.click(); + } + + public static WebElement Waitfunctionforbuttons(String element, int timeout) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout); + return wait.until(ExpectedConditions.elementToBeClickable(By.xpath(element))); + } + + public static WebElement waitToButtonSubmitForTesting() { + return Waitfunctionforbuttons("//*[@data-tests-id='submitForTesting']", 10); + } + + public static WebElement waitToFinishButtonEnabled() { + return Waitfunctionforbuttons("//button[@data-tests-id='Finish']", 10); + } + + public static WebElement waitToNextButtonEnabled() { + return Waitfunctionforbuttons("//button[@data-tests-id='Next']", 10); + } + + public static WebElement waitToHomeMenu() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-home']", 10); + } + + public static WebElement waitToCatalogMenu() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-button-catalog']", 10); + } + + public static WebElement waitSearch() { + return Waitfunctionforbuttons("//*[@data-tests-id='main-menu-input-search']", 10); + } + + public static WebElement waitSubmitforTestingCard() { + return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-SubmitforTesting']", 10); + } + + public static WebElement waitViewCard() { + return Waitfunctionforbuttons("//*[@data-tests-id='i-sdc-dashboard-card-menu-item-View']", 5); + } + +// public static void waitOpenCard(String requiredElementUniqueId) throws Exception { +// WebElement menu = GeneralUIUtils.getDriver() +// .findElement(By.xpath("//*[@data-tests-id='" + requiredElementUniqueId + "']")); +// GeneralUIUtils.hoverOnAreaByTestId(menu); +// } + + public static void fillResourceGeneralInformationPage(ResourceReqDetails resource, User user, boolean isNewResource) { + try { + ResourceGeneralPage.defineName(resource.getName()); + ResourceGeneralPage.defineDescription(resource.getDescription()); + ResourceGeneralPage.defineCategory(resource.getCategories().get(0).getSubcategories().get(0).getName()); + ResourceGeneralPage.defineVendorName(resource.getVendorName()); + ResourceGeneralPage.defineVendorRelease(resource.getVendorRelease()); + if (isNewResource){ + ResourceGeneralPage.defineTagsList(resource, new String[] { "This-is-tag", "another-tag", "Test-automation-tag" }); + } + else{ + ResourceGeneralPage.defineTagsList(resource, new String[] { "one-more-tag" }); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void fillMaxValueResourceGeneralInformationPage(ResourceReqDetails resource) { + String stringPattern = "ABCDabcd123456"; + GeneralUIUtils.addStringtoClipboard(buildStringFromPattern(stringPattern, 5000)); + ResourceGeneralPage.defineNameWithPaste(); + ResourceGeneralPage.defineDescriptionWithPaste(); + ResourceGeneralPage.defineVendorNameWithPaste(); + ResourceGeneralPage.defineVendorReleaseWithPaste(); +// ResourceGeneralPage.defineName(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineDescription(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineVendorName(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineVendorRelease(buildStringFromPattern(stringPattern, 5000)); +// ResourceGeneralPage.defineTagsList(resource, new String[] { buildStringFromPattern(stringPattern, 5000) }); + ResourceGeneralPage.defineTagsListWithPaste(); + GeneralUIUtils.waitForAngular(); + } + + public static String buildStringFromPattern(String stringPattern, int stringLength){ + char[] chars = stringPattern.toCharArray(); + StringBuilder sb = new StringBuilder(); + Random random = new Random(); + for (int i = 0; i < stringLength; i++) { + char c = chars[random.nextInt(chars.length)]; + sb.append(c); + } + return sb.toString(); + } + + public static void fillNewResourceValues(ResourceReqDetails resource, User user) throws Exception { + fillResourceGeneralInformationPage(resource, user, true); + GeneralPageElements.clickCreateButton(); + // selectIcon(); + } + + // coded by teddy. + + public static WebElement waitfunctionforallelements(String element) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 5); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@*='" + element + "']"))); + } + + public static WebElement waitFunctionForaGetElements(String element, int timeout) { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), timeout); + return wait.until( + ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + element + "']"))); + } + + public static void getVFCGeneralInfo(ResourceReqDetails resource, User user) throws InterruptedException { + Thread.sleep(2000); + String version = GeneralUIUtils.getWebElementsListByTestID("versionvalue").get(0).getText().substring(1); + String name = GeneralUIUtils.getWebElementByTestID("name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + String vendorName = GeneralUIUtils.getWebElementByTestID("vendorName").getAttribute("value"); + String vendorRelease = GeneralUIUtils.getWebElementByTestID("vendorRelease").getAttribute("value"); + List<WebElement> tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String AttContact = GeneralUIUtils.getWebElementByTestID("attContact").getAttribute("value"); + System.out.println(resource.getVersion()); + assertTrue(resource.getVersion().equals(version)); + assertTrue(resource.getName().equals(name)); + assertTrue(resource.getDescription().equals(description)); + System.out.println(resource.getVendorName()); + System.out.println(resource.getVendorRelease()); + assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category)); + assertTrue(resource.getVendorName().equals(vendorName)); + assertTrue(resource.getVendorRelease().equals(vendorRelease)); + assertTrue(resource.getCreatorUserId().equals(AttContact)); + assertEquals(type.substring(0, index), resource.getResourceType()); + + for (int i = 0; i < tags.size(); i++) { + assertEquals(resource.getTags().get(i), tags.get(i).getText()); + } + } + + public static void getGeneralInfo(ResourceReqDetails resource, User user) { + + // clickMore(); + // String + // componentType=waitFunctionForaGetElements("componentType",3).getText(); + // String version=waitFunctionForaGetElements("version",3).getText(); + // String + // category=waitFunctionForaGetElements("category",3).getText();//get + // right panel Category. + // String + // resourceType=waitFunctionForaGetElements("resourceType",3).getText();//get + // right panel SubCategory. + // String date=waitfunctionforelements("creationDate",3).getText(); + // String aouthor=waitfunctionforallelements("author'",3).getText(); + // String + // vendorName=waitFunctionForaGetElements("vendorName",3).getText(); + // String + // vendorRelease=waitFunctionForaGetElements("vendorRelease",3).getText(); + // String + // AttContact=waitFunctionForaGetElements("attContact",3).getText(); + // String + // Description=waitFunctionForaGetElements("description",3).getText(); + List<WebElement> tags = GeneralUIUtils.getWebElementsListByTestID("tag"); + // // String TagVF=waitFunctionForaGetElements("tag",3).getText(); + // assertTrue(componentType.equals("RESOURCE")); + // assertTrue(version.equals(resource.getVersion())); + // assertTrue(category.equals(resource.getCategories().get(0).getName())); + // assertEquals(resourceType,resource.getResourceType()); + // // assertEquals(Date,resource.getCreationDate()); + // // assertEquals(Aouthor,resource.getCreatorFullName()); + // assertTrue(vendorName.equals(resource.getVendorName())); + // assertTrue(vendorRelease.equals(resource.getVendorRelease())); + // assertTrue(AttContact.equals(resource.getAttContact())); + // assertTrue(Description.equals(resource.getDescription()+"\nLess")); + for (WebElement tag : tags) { + System.out.println(resource.getTags().get(0)); + } + } + + public static void getGeneralInfoForTags(ResourceReqDetails resource, User user) { + + clickMore(); + String componentType = waitFunctionForaGetElements("componentType", 3).getText(); + String version = waitFunctionForaGetElements("version", 3).getText(); + String category = waitFunctionForaGetElements("category", 3).getText();// get + // right + // panel + // Category. + String resourceType = waitFunctionForaGetElements("resourceType", 3).getText();// get + // right + // panel + // SubCategory. + String date = GeneralUIUtils.getWebElementByClassName("creationDate").getText(); + String aouthor = waitfunctionforallelements("author'").getText(); + String vendorName = waitFunctionForaGetElements("vendorName", 3).getText(); + String vendorRelease = waitFunctionForaGetElements("vendorRelease", 3).getText(); + String attContact = waitFunctionForaGetElements("attContact", 3).getText(); + String description = waitFunctionForaGetElements("description", 3).getText(); + List<WebElement> tags = GeneralUIUtils.getWebElementsListByTestID("tag"); + assertTrue(componentType.equals("RESOURCE")); + assertTrue(version.equals(resource.getVersion())); + assertTrue(category.equals(resource.getCategories().get(0).getName())); + assertEquals(resourceType, resource.getResourceType()); + // assertEquals(Date,resource.getCreationDate()); + // assertEquals(Aouthor,resource.getCreatorFullName()); + assertTrue(vendorName.equals(resource.getVendorName())); + assertTrue(vendorRelease.equals(resource.getVendorRelease())); + assertTrue(attContact.equals(resource.getContactId())); + assertTrue(description.equals(resource.getDescription() + "\nLess")); + assertTrue(tags.equals("Tag-150")); + } + + public static WebElement searchVFNameInWorkspace(ResourceReqDetails resource, User user) throws Exception { + + List<WebElement> findElements = GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@data-tests-id='" + resource.getUniqueId() + "']")); + assertNotNull("did not find any elements", findElements); + for (WebElement webElement : findElements) { + if (webElement.getText().contains(resource.getUniqueId())) { + System.out.println("I find it"); + return webElement; + } + } + return null; + } + + public static Boolean searchCheckOutWorkspace(ResourceReqDetails resource, User user, + CheckBoxStatusEnum checkBoxStatusEnum) throws Exception { + + List<WebElement> findElements = GeneralUIUtils.getDriver() + .findElements(By.xpath("//div[@data-tests-id='component.lifecycleState']")); + assertNotNull("did not find any elements", findElements); + for (WebElement webElement : findElements) { + if (!webElement.getAttribute("class").contains(checkBoxStatusEnum.name())) { + return false; + } + } + return true; + } + + // coded by tedy. + public static void validateWithRightPalett(ResourceReqDetails resource, User user) { + // String + // Type=Waitfunctionforallelements("sharingService.selectedEntity.getTypeForView()",3).getText(); + String ResourceType = waitfunctionforallelements("selectedComponent.resourceType").getText(); + System.out.println(ResourceType); + String Version = waitfunctionforallelements("selectedComponent.version").getText(); + String Category = waitfunctionforallelements("selectedComponent.categories[0].name").getText();// get + // right + // panel + // Category. + String CanvasSubCategory = waitfunctionforallelements("selectedComponent.categories[0].subcategories[0].name") + .getText();// get right panel SubCategory. + // String Date=Waitfunctionforelements("selectedComponent.creationDate | + // date: 'MM/dd/yyyy'").getText(); + // String + // Aouthor=waitfunctionforallelements("selectedComponent.creatorFullName'").getText(); + String VendorName = waitfunctionforallelements("selectedComponent.vendorName").getText(); + String VendorRelease = waitfunctionforallelements("selectedComponent.vendorRelease").getText(); + String AttContact = waitfunctionforallelements("selectedComponent.attContact").getText(); + String Description = waitfunctionforallelements("selectedComponent.description").getText(); + String TagVF = waitfunctionforallelements("tag").getText(); + AssertJUnit.assertEquals(ResourceType, resource.getResourceType()); + AssertJUnit.assertEquals(Version, resource.getVersion()); + AssertJUnit.assertEquals(Category, resource.getCategories().get(0).getName()); + AssertJUnit.assertEquals(CanvasSubCategory, + resource.getCategories().get(0).getSubcategories().get(0).getName()); + // assertEquals(Date,resource.getCreationDate()); + // assertEquals(Aouthor,resource.getCreatorFullName()); + AssertJUnit.assertEquals(VendorName, resource.getVendorName()); + AssertJUnit.assertEquals(VendorRelease, resource.getVendorRelease()); + AssertJUnit.assertEquals(AttContact, resource.getContactId()); + AssertJUnit.assertEquals(Description, resource.getDescription() + "\nLess"); + AssertJUnit.assertEquals(TagVF, "qa123"); + } + + public static void clickMore() { + WebElement clickButtonSubmit = GeneralUIUtils.getDriver() + .findElement(By.className("ellipsis-directive-more-less")); + clickButtonSubmit.click(); + } + + public static RestResponse createResourceInUI(ResourceReqDetails resource, User user) + throws Exception, AWTException { + System.out.println("creating resource..."); + fillNewResourceValues(resource, user); + RestResponse getCreatedResource = RestCDUtils.getResource(resource, user); + AssertJUnit.assertEquals("Did not succeed to get any resource", HttpStatus.SC_OK, + getCreatedResource.getErrorCode().intValue()); + + return getCreatedResource; + } + + public static void createResource(ResourceReqDetails resource, User user) throws Exception { + ExtentTestActions.log(Status.INFO, "Going to create a new VF."); + WebElement addVFButton = null; + try { + GeneralUIUtils.ultimateWait(); + try{ + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + addVFButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + } + catch (Exception e){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resource.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "Add VF button is not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + showButtonsADD(); + addVFButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + } + addVFButton.click(); + GeneralUIUtils.ultimateWait(); + } + catch (Exception e ) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on ADD VF button, retrying ... ")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + fillResourceGeneralInformationPage(resource, user, true); + resource.setVersion("0.1"); + GeneralPageElements.clickCreateButton(); + } + + public static void updateResource(ResourceReqDetails resource, User user){ + ResourceGeneralPage.defineContactId(resource.getContactId()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating General screen fields ...")); + fillResourceGeneralInformationPage(resource, user, false); + ResourceGeneralPage.clickUpdateButton(); + } + + + + public static RestResponse updateResourceInformationPage(ResourceReqDetails resource, User user) + throws Exception, AWTException { + + fillResourceGeneralInformationPage(resource, user, true); + GeneralPageElements.clickCreateButton(); + return null; + + } + + public static RestResponse checkInResourceInUI(ResourceReqDetails resource, User user) throws Exception { + + WebElement ASDCLink = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-header-logo-link")); + ASDCLink.click(); + Thread.sleep(2000); + + List<WebElement> listFormInput = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-left-sidebar-nav-item")); + WebElement addPropertyElement = listFormInput.get(0); + addPropertyElement.click(); + Thread.sleep(2000); + + WebElement searchResource = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-header-catalog-search-input")); + searchResource.sendKeys("newresource4test"); + + Thread.sleep(1000); + + WebElement buttonClickMenu = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-dashboard-card-menu-button")); + buttonClickMenu.click(); + + WebElement clickMenu = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu")); + clickMenu.click(); + + List<WebElement> clickCheckIn = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-dashboard-card-menu-item")); + WebElement clickCheckInMenu = clickCheckIn.get(1); + clickCheckInMenu.click(); + + WebElement descriptionForSubmit = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-modal-body-comment")); + descriptionForSubmit.sendKeys("checkin resource"); + Thread.sleep(2000); + WebElement clickButtonSubmitTwo = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-btn-blue")); + clickButtonSubmitTwo.click(); + Thread.sleep(2000); + + WebElement buttonClickMenu1 = GeneralUIUtils.getDriver() + .findElement(By.className("w-sdc-dashboard-card-menu-button")); + buttonClickMenu1.click(); + + WebElement clickMenu1 = GeneralUIUtils.getDriver().findElement(By.className("w-sdc-dashboard-card-menu")); + clickMenu1.click(); + + List<WebElement> clickCheckOut = GeneralUIUtils.getDriver() + .findElements(By.className("i-sdc-dashboard-card-menu-item")); + WebElement clickCheckOutMenu = clickCheckOut.get(0); + clickCheckOutMenu.click(); + + Thread.sleep(3000); + RestResponse getResource = RestCDUtils.getResource(resource, user); + AssertJUnit.assertEquals("Did not succeed to get resource after create", 200, + getResource.getErrorCode().intValue()); + return getResource; + + } + + public static String lifeCycleStateUI() throws InterruptedException { + return GeneralUIUtils.getWebElementByTestID("formlifecyclestate").getText(); + } + + public static List<String> catalogFilterResourceCategoriesChecBox(ResourceCategoriesNameEnum enumName) + throws Exception { + List<String> categories = Arrays.asList(); + switch (enumName) { + case APPLICATIONL4: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "defaulticon", "vl", "cp", "call_controll", "borderElement", + "network", "firewall", "database", "loadBalancer"); + break; + case APPLICATION_SERVER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon"); + break; + case BORDER_ELEMENT: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("borderElement", "vl", "cp", "defaulticon"); + break; + case CALL_CONTROL: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("call_controll", "vl", "cp", "defaulticon"); + break; + case COMMON_NETWORK_RESOURCES: + GeneralUIUtils.getWebElementByLinkText("Common Network Resources").click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case CONNECTION_POINTS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("cp", "defaulticon"); + break; + case DATABASE: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "vl", "cp", "defaulticon"); + break; + case DATABASE_GENERIC: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "vl", "cp", "defaulticon"); + break; + case FIREWALL: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("firewall", "vl", "cp", "defaulticon"); + break; + case GATEWAY: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("gateway", "vl", "cp", "defaulticon"); + break; + case INFRASTRUCTURE: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("connector", "vl", "cp", "defaulticon"); + break; + case INFRASTRUCTUREL23: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("ucpe", "vl", "cp", "defaulticon"); + break; + case LAN_CONNECTORS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon"); + break; + case LOAD_BALANCER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("loadBalancer", "vl", "cp", "defaulticon"); + break; + case MEDIA_SERVERS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case NETWORKL4: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case NETWORK_ELEMENTS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("port", "defaulticon", "network", "connector", "vl", "cp"); + break; + case NETWORK_L23: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "defaulticon", "cp", "router", "port", "connector", "gateway", + "ucpe"); + break; + case NETWORK_CONNECTIVITY: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "vl", "cp", "defaulticon"); + break; + case GENERIC: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("database", "port", "loadBalancer", "vl", "cp", "objectStorage", "compute", + "defaulticon", "ucpe", "network", "connector"); + break; + case ABSTRACT: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("objectStorage", "compute", "defaulticon", "cp", "vl"); + break; + case Router: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("router", "vl", "cp", "defaulticon"); + break; + case VIRTUAL_LINKS: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("vl", "defaulticon"); + break; + case WAN_Connectors: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("network", "port", "connector", "vl", "cp", "defaulticon"); + break; + case WEB_SERVER: + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + categories = Arrays.asList("applicationServer", "vl", "cp", "defaulticon"); + break; + } + return categories; + } + + public static void deleteVersionInUI() throws Exception { + + waitToDeleteVersion().click(); + ResourceUIUtils.clickButtonBlue(); + } + + public static void selectTabInRightPallete(String className) throws Exception { + WebElement tab = GeneralUIUtils.getWebElementByClassName(className); + tab.click(); + } + + public static WebElement waitToDeleteVersion() { + return Waitfunctionforbuttons("//*[@data-tests-id='deleteVersion']", 10); + } + + public static WebElement rihtPanelAPI() { + return waitFunctionForaGetElements("tab-api", 10); + } + + /** + * Click on HTML element. + * + * @param dataTestId + * @throws Exception + */ + public static void getWebElementByTestID(String dataTestId) throws Exception { + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 20); + WebElement element = wait + .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + element.click(); + // wait.until(ExpectedConditions.elemetto) + // WebElement serviceButton = + // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + // + dataTestId + "']")); + // serviceButton. + // serviceButton.click(); + } + + /** + * Move to HTML element by class name. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ +// public static void moveToHTMLElementByClassName(String className) { +// Actions actions = new Actions(GeneralUIUtils.getDriver()); +// final WebElement createButtonsArea = GeneralUIUtils +// .retryMethodOnException(() -> GeneralUIUtils.getDriver().findElement(By.className(className))); +// actions.moveToElement(createButtonsArea).perform(); +// } + + /** + * Move to HTML element by element id. When moving to the HTML element, it + * will raise hover event. + * + * @param className + */ +// static void moveToHTMLElementByDataTestId(String dataTestId) { +// // WebElement hoverArea = +// // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" +// // + dataTestId + "']")); +// WebElement hoverArea = GeneralUIUtils.waitForElementVisibility(dataTestId); +// // WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), +// // 30); +// // wait.until(ExpectedConditions.visibilityOf(hoverArea)); +// +// Actions actions = new Actions(GeneralUIUtils.getDriver()); +// actions.moveToElement(hoverArea).perform(); +// } + + // public static ResourceReqDetails createResourceInUI(User user){ + // try{ + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(ResourceTypeEnum.VF); + // ResourceUIUtils.moveToHTMLElementByClassName("w-sdc-dashboard-card-new"); + // ResourceUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + // GeneralUIUtils.waitForLoader(); + //// GeneralUIUtils.sleep(1000); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + // catch( Exception e){ + // throw new RuntimeException(e); + // } + // } + + /** + * Import VFC + * + * @param user + * @param filePath + * @param fileName + * @return + * @throws Exception + */ + + public static void importVfc(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VFC resource ", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(); + } + + public static void importVfcNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + } + + + public static void importVfFromCsar(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(10*60); +// GeneralUIUtils.ultimateWait(); "don't change import of csar can take longer then 3 minutes" + GeneralUIUtils.waitForLoader(10*60); + } + + public static void importVfFromCsarNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s, Create button will not be clicked", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()){ + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try{ + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralUIUtils.waitForLoader(10*60); + } + + public static void updateVfWithCsar(String filePath, String fileName) { + ExtentTestActions.log(Status.INFO, "Updating VF with updated CSAR file named " + fileName); + WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.GeneralElementsEnum.UPLOAD_FILE_INPUT.getValue()); + browseWebElement.sendKeys(filePath + fileName); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickUpdateButton(); + GeneralUIUtils.waitForLoader(); + ExtentTestActions.log(Status.INFO, "VF is updated."); + } + + + + // public static ResourceReqDetails importVfcInUI(User user, String + // filePath, String fileName, ResourceTypeEnum resourceType) { + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(resourceType); + // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue()); + // + // // Insert file to the browse dialog + // final WebElement browseWebElement = + // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + // browseWebElement.sendKeys(filePath + fileName); + // + // // Fill the general page fields. + // GeneralUIUtils.waitForLoader(); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + + /** + * Import VF + * + * @param user + * @param filePath + * @param fileName + * @return + * @throws Exception + */ + // public static ResourceReqDetails importVfInUI(User user, String filePath, + // String fileName) throws Exception { + // ResourceReqDetails defineResourceDetails = + // defineResourceDetails(ResourceTypeEnum.VF); + // ResourceUIUtils.moveToHTMLElementByDataTestId(Dashboard.IMPORT_AREA.getValue()); + // + // // Insert file to the browse dialog + // final WebElement browseWebElement = + // GeneralUIUtils.getWebElementByDataTestId(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + // browseWebElement.sendKeys(filePath + fileName); + // + // // Fill the general page fields. + // GeneralUIUtils.waitForLoader(); + // fillResourceGeneralInformationPage(defineResourceDetails, user); + // GeneralPageElements.clickCreateButton(); + // return defineResourceDetails; + // } + + // public static ResourceReqDetails defineResourceDetails(ResourceTypeEnum + // resourceType) { + // ResourceReqDetails resource = new ResourceReqDetails(); + // resource = ElementFactory.getDefaultResource(NormativeTypesEnum.ROOT, + // ResourceCategoryEnum.APPLICATION_L4_CALL_CONTROL); + // resource.setVersion(INITIAL_VERSION); + // resource.setIcon(ICON_RESOURCE_NAME); + // resource.setResourceType(resourceType.toString()); + // resource.setName(getRandomComponentName(RESOURCE_NAME_PREFIX)); + // + // SetupCDTest.setCreatedComponents(Arrays.asList(resource)); + // + // return resource; + // } + + protected static String getRandomComponentName(String prefix) { + return prefix + new Random().nextInt(10000); + } + + public static ImmutablePair<String, String> getFirstRIPos(ResourceReqDetails createResourceInUI, User user) { + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String xPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posX"); + String yPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posY"); + return new ImmutablePair<String, String>(xPosPostDrag, yPosPostDrag); + + } + + public static WebElement getErrorMessageText(WebDriver driver, String text) throws Exception { + + return GeneralUIUtils.getWebElementByClassName(text); + + } + + public static void fillGeneralInfoValuesAndIcon(ResourceReqDetails resource, User user) throws Exception { + fillResourceGeneralInformationPage(resource, user, true); + + GeneralPageElements.clickCreateButton(); + + selectRandomResourceIcon(); + } + + // coded by teddy. + public static void getVFCGeneralInfoAndValidate(ResourceReqDetails resource, User user) + throws InterruptedException { + Thread.sleep(2000); + WebDriver driver = GeneralUIUtils.getDriver(); + String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText(); + String name = GeneralUIUtils.getWebElementByTestID( "name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID( "description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + String vendorName = GeneralUIUtils.getWebElementByTestID( "vendorName").getAttribute("value"); + String vendorRelease = GeneralUIUtils.getWebElementByTestID( "vendorRelease").getAttribute("value"); + List<WebElement> tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String AttContact = GeneralUIUtils.getWebElementByTestID( "attContact").getAttribute("value"); + System.out.println(resource.getVersion()); + assertTrue(resource.getVersion().equals(version.substring(1))); + assertTrue(resource.getName().equals(name)); + assertTrue(resource.getDescription().equals(description)); + System.out.println(resource.getVendorName()); + System.out.println(resource.getVendorRelease()); + assertTrue(resource.getCategories().get(0).getSubcategories().get(0).getName().equals(category)); + assertTrue(resource.getVendorName().equals(vendorName)); + assertTrue(resource.getVendorRelease().equals(vendorRelease)); + assertTrue(resource.getCreatorUserId().equals(AttContact)); + assertEquals(type.substring(0, index), resource.getResourceType()); + + for (int i = 0; i < tags.size(); i++) { + assertEquals(resource.getTags().get(i), tags.get(i).getText()); + } + } + + public static RestResponse createResourceNG(ResourceReqDetails resource, User user) throws Exception, AWTException { + + GeneralUIUtils.hoverOnAreaByTestId("w-sdc-dashboard-card-new"); + ResourceUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_VF.getValue()); + fillResourceGeneralInformationPage(resource, user, true); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue()); + return null; + + } + + public static void showButtons(){ + String parentElementClassAttribute = "sdc-dashboard-import-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + public static void showButtonsADD(){ + try { + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } catch (Exception e ){ + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + public static void clickOnElementByText(String textToClick, String customizationFoLog){ + String customizationFoLogLocal = customizationFoLog != null ? customizationFoLog : ""; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s %s", textToClick, customizationFoLogLocal)); + GeneralUIUtils.clickOnElementByText(textToClick); + } +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java new file mode 100644 index 0000000000..b2bad99d2a --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java @@ -0,0 +1,344 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory; +import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils; + +import com.aventstack.extentreports.Status; + +public class RestCDUtils { + + private static void setResourceUniqueIdAndUUID(ComponentReqDetails element, RestResponse getResourceResponse) { + element.setUniqueId(ResponseParser.getUniqueIdFromResponse(getResourceResponse)); + element.setUUID(ResponseParser.getUuidFromResponse(getResourceResponse)); + } + + public static RestResponse getResource(ResourceReqDetails resource, User user) { + final String getResourceMsg = "Trying to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String succeedGetResourceMsg = "Succeeded to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String failedGetResourceMsg = "Failed to get resource named " + resource.getName() + " with version " + resource.getVersion(); + try { + ExtentTestActions.log(Status.INFO, getResourceMsg); + System.out.println(getResourceMsg); + GeneralUIUtils.sleep(1000); + RestResponse getResourceResponse = null; + String reourceUniqueId = resource.getUniqueId(); + if (reourceUniqueId != null) { + getResourceResponse = ResourceRestUtils.getResource(reourceUniqueId); + if (getResourceResponse.getErrorCode().intValue() == 200) { + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + } + return getResourceResponse; + } + JSONObject getResourceJSONObject = null; + getResourceResponse = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), resource.getName(), resource.getVersion()); + if (getResourceResponse.getErrorCode().intValue() == 200) { +// JSONArray jArray = new JSONArray(getResourceResponse.getResponse()); +// for (int i = 0; i < jArray.length(); i++) { +// getResourceJSONObject = jArray.getJSONObject(i); +// String resourceType = ResponseParser.getValueFromJsonResponse(getResourceJSONObject.toString(), "resourceType"); +// if (resourceType.equals(resource.getResourceType())) { +// getResourceResponse.setResponse(getResourceJSONObject.toString()); + setResourceUniqueIdAndUUID(resource, getResourceResponse); + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + return getResourceResponse; +// } +// } + } + ExtentTestActions.log(Status.INFO, failedGetResourceMsg); + return getResourceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static RestResponse getService(ServiceReqDetails service, User user) { + try { + Thread.sleep(3500); + RestResponse getServiceResponse = ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(), + service.getVersion()); + if (getServiceResponse.getErrorCode().intValue() == 200) { + setResourceUniqueIdAndUUID(service, getServiceResponse); + } + return getServiceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + public static RestResponse getProduct(ProductReqDetails product, User user) { + try { + Thread.sleep(3500); + RestResponse getProductResponse = ProductRestUtils.getProductByNameAndVersion(product.getName(), + product.getVersion(), user.getUserId()); + if (getProductResponse.getErrorCode().intValue() == 200) { + setResourceUniqueIdAndUUID(product, getProductResponse); + } + return getProductResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static Map<String, String> getAllElementVersionsFromResponse(RestResponse getResource) throws Exception { + Map<String, String> versionsMap = new HashMap<String, String>(); + try { + ObjectMapper mapper = new ObjectMapper(); + + JSONObject object = new JSONObject(getResource.getResponse()); + versionsMap = mapper.readValue(object.get("allVersions").toString(), Map.class); + + } catch (Exception e) { + e.printStackTrace(); + return versionsMap; + + } + + return versionsMap; + } + + public static void deleteElementVersions(Map<String, String> elementVersions, boolean isBeforeTest, Object clazz, + User user) throws Exception { + Iterator<String> iterator = elementVersions.keySet().iterator(); + while (iterator.hasNext()) { + String singleVersion = iterator.next(); + String uniqueId = elementVersions.get(singleVersion); + RestResponse deleteResponse = null; + if (clazz instanceof ServiceReqDetails) { + deleteResponse = ServiceRestUtils.deleteServiceById(uniqueId, user.getUserId()); + } else if (clazz instanceof ResourceReqDetails) { + deleteResponse = ResourceRestUtils.deleteResource(uniqueId, user.getUserId()); + } else if (clazz instanceof ProductReqDetails) { + deleteResponse = ProductRestUtils.deleteProduct(uniqueId, user.getUserId()); + } + + if (isBeforeTest) { + assertTrue(deleteResponse.getErrorCode().intValue() == 204 + || deleteResponse.getErrorCode().intValue() == 404); + } else { + assertTrue(deleteResponse.getErrorCode().intValue() == 204); + } + } + } + + public static void deleteAllResourceVersionsAfterTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) { + try { + deleteAllComponentVersion(false, componentDetails, getObjectResponse, user); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void deleteAllResourceVersionsBeforeTest(ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + deleteAllComponentVersion(true, componentDetails, getObjectResponse, user); + } + + public static void deleteAllComponentVersion(boolean isBeforeTest, ComponentReqDetails componentDetails, + RestResponse getObjectResponse, User user) throws Exception { + if (getObjectResponse.getErrorCode().intValue() == 404) + return; + Map<String, String> componentVersionsMap = getAllElementVersionsFromResponse(getObjectResponse); + System.out.println("deleting..."); + deleteElementVersions(componentVersionsMap, isBeforeTest, componentDetails, user); + componentDetails.setUniqueId(null); + } + + + + public static String getExecutionHostAddress() { + + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·"); + System.out.println(computerName); + if (computerName.indexOf(".") > -1) + computerName = computerName.substring(0, + computerName.indexOf(".")).toUpperCase(); + } catch (UnknownHostException e) { + System.out.println("Uknown hostAddress"); + } + return computerName != null ? computerName : "Uknown hostAddress"; + } + + public static Map<String, List<Component>> getCatalogAsMap() throws IOException { + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse catalog = CatalogRestUtils.getCatalog(defaultAdminUser.getUserId()); + Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser + .convertCatalogResponseToJavaObject(catalog.getResponse()); + return convertCatalogResponseToJavaObject; + } + + public static Map<String, List<CategoryDefinition>> getCategories() throws Exception { + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + Map<String,List<CategoryDefinition>> map = new HashMap<String,List<CategoryDefinition>>(); + + + RestResponse allResourceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.RESOURCE_PARAM_NAME); + RestResponse allServiceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.SERVICE_PARAM_NAME); + + List<CategoryDefinition> parsedResourceCategories = ResponseParser.parseCategories(allResourceCategories); + List<CategoryDefinition> parsedServiceCategories = ResponseParser.parseCategories(allServiceCategories); + + map.put(ComponentTypeEnum.RESOURCE_PARAM_NAME, parsedResourceCategories); + map.put(ComponentTypeEnum.SERVICE_PARAM_NAME, parsedServiceCategories); + + return map; + } + + public static void deleteCreatedComponents(Map<String, List<Component>> map) throws IOException { + + System.out.println("going to delete all created components..."); + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + final String userId = defaultAdminUser.getUserId(); + + List<Component> resourcesArrayList = map.get("products"); + List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("Ci")).map(e -> e.getUniqueId()) + .collect(Collectors.toList()); + for (String uId : collect) { + ProductRestUtils.deleteProduct(uId, userId); + } + + resourcesArrayList = map.get("services"); + collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")).map(e -> e.getUniqueId()) + .collect(Collectors.toList()); + for (String uId : collect) { + ServiceRestUtils.markServiceToDelete(uId, userId); + } + ServiceRestUtils.deleteMarkedServices(userId); + + resourcesArrayList = map.get("resources"); + collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) + .map(e -> e.getUniqueId()).collect(Collectors.toList()); + for (String uId : collect) { + ResourceRestUtils.markResourceToDelete(uId, userId); + } + ResourceRestUtils.deleteMarkedResources(userId); + + + + + + } + + public static void deleteCategoriesByList(List<CategoryDefinition> listCategories, String componentType, User user) throws Exception { + + for (CategoryDefinition categoryDefinition : listCategories) { + if (categoryDefinition.getName().toLowerCase().startsWith("ci")) { + List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories(); + if (subcategories != null) { + for (SubCategoryDefinition subCategoryDefinition : subcategories) { + + CategoryRestUtils.deleteSubCategory(subCategoryDefinition.getUniqueId(), + categoryDefinition.getUniqueId(), user.getUserId(), + componentType); + } + } + + CategoryRestUtils.deleteCategory(categoryDefinition.getUniqueId(), user.getUserId(), + componentType); + + } + } + } + + public static String getUserRole(User reqUser, User user){ + try{ + RestResponse getUserRoleResp = UserRestUtils.getUserRole(reqUser, user); + JSONObject jObject = new JSONObject(getUserRoleResp.getResponse()); + return jObject.getString("role"); + } + catch(Exception e){ + return null; + } + } + + public static RestResponse getUser(User reqUser, User user){ + try{ + return UserRestUtils.getUser(reqUser, user); + } + catch(Exception e){ + return null; + } + } + + /*************************************/ + + public static void deleteOnDemand() throws IOException { + Config config = DriverFactory.getConfig(); + if(!config.getSystemUnderDebug()){ + deleteCreatedComponents(getCatalogAsMap()); + }else{ + System.out.println("Accordindig to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ..."); + } + } + + public static void deleteCategories(User user) throws Exception { + Map<String, List<CategoryDefinition>> categoriesMap = getCategories(); + List<CategoryDefinition> listCategories = categoriesMap.get(ComponentTypeEnum.RESOURCE_PARAM_NAME); + deleteCategoriesByList(listCategories, ComponentTypeEnum.RESOURCE_PARAM_NAME, user); + listCategories = categoriesMap.get(ComponentTypeEnum.SERVICE_PARAM_NAME); + deleteCategoriesByList(listCategories, ComponentTypeEnum.SERVICE_PARAM_NAME, user); + } + +} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java new file mode 100644 index 0000000000..8b07e621d9 --- /dev/null +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ServiceUIUtils.java @@ -0,0 +1,286 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.awt.AWTException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceCategoriesNameEnum; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum; +import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.aventstack.extentreports.Status; + +public class ServiceUIUtils { + + protected static WebDriver driver; + + public ServiceUIUtils(TestName name, String className) { + super(); + } + + public static String defineServiceName(String Name) { + WebElement serviceName = GeneralUIUtils.getWebElementByTestID("name"); + serviceName.clear(); + serviceName.sendKeys(Name); + return Name; + } + + public void moveResourceInstanceToCanvasUI() throws Exception { + List<WebElement> moveResource = driver.findElements(By.className("sprite-resource-icons")); + WebElement moveResourceToCanvasResourceOne = moveResource.get(0); + // WebElement moveResource = + // driver.findElement(By.className("sprite-resource-icons")); + Actions action = new Actions(driver); + action.moveToElement(moveResourceToCanvasResourceOne); + action.clickAndHold(moveResourceToCanvasResourceOne); + action.moveByOffset(635, 375); + action.release(); + action.perform(); + WebElement moveResourceToCanvasResourceTwo = moveResource.get(1); + action.moveToElement(moveResourceToCanvasResourceTwo); + action.clickAndHold(moveResourceToCanvasResourceTwo); + action.moveByOffset(535, 375); + action.release(); + action.perform(); + WebElement moveResourceToCanvasResourceTree = moveResource.get(2); + action.moveToElement(moveResourceToCanvasResourceTree); + action.clickAndHold(moveResourceToCanvasResourceTree); + action.moveByOffset(435, 375); + action.release(); + action.perform(); + Thread.sleep(2000); + } + + public static String catalogFilterServiceCategoriesChecBox(ServiceCategoriesNameEnum enumName) throws Exception { + String Type = null; + GeneralUIUtils.getWebElementByTestID(enumName.getValue()).click(); + return Type; + } + + public static List<String> catalogServiceTypeChecBox(ServiceCategoriesNameEnum enumtype) throws Exception { + List<String> categories = null; + switch (enumtype) { + case NETWORK_L13: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("network_l_1-3"); + break; + case NETWORKL4: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("network_l_4 "); + break; + case MOBILITY: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("mobility"); + break; + case VOIPCALL_CONTROL: + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + categories = Arrays.asList("call_controll "); + break; + } + return categories; + } + + public static WebElement waitToNextButtonEnabled() { + return GeneralUIUtils.getWebElementByTestID("Next"); + } + + public static WebElement waitToFinishButtonEnabled() { + return GeneralUIUtils.getWebElementByTestID("Finish"); + } + + public static WebElement deleteServiceInUI() { + + return GeneralUIUtils.getWebElementByTestID("deleteVersion"); + } + + // get the service view data for validate. + // created by tedy. + public static void getServiceGeneralInfo(ServiceReqDetails service, User user) throws InterruptedException { + Thread.sleep(2000); + String version = GeneralUIUtils.getSelectList(null, "versionHeader").getFirstSelectedOption().getText() + .substring(1); + String name = GeneralUIUtils.getWebElementByTestID("name").getAttribute("value"); + String description = GeneralUIUtils.getWebElementByTestID("description").getAttribute("value"); + String category = GeneralUIUtils.getSelectList(null, "selectGeneralCategory").getFirstSelectedOption() + .getText(); + List<WebElement> tags = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-text"); + String type = GeneralUIUtils.getWebElementsListByTestID("type").get(1).getText(); + int index = type.lastIndexOf(":"); + System.out.println(type.substring(0, index)); + String attContact = GeneralUIUtils.getWebElementByTestID("attContact").getAttribute("value"); + String pmatt = GeneralUIUtils.getWebElementByTestID("pmatt").getAttribute("value"); + System.out.println(service.getVersion()); + assertTrue(service.getVersion().equals(version)); + assertTrue(service.getName().equals(name)); + assertTrue(service.getDescription().equals(description)); + assertTrue(service.getCategories().get(0).getName().equals(category)); + System.out.println(service.getContactId()); + assertTrue(service.getContactId().equals(attContact)); + assertTrue(service.getProjectCode().equals(pmatt)); + for (int i = 0; i < tags.size(); i++) { + assertEquals(service.getTags().get(i), tags.get(i).getText()); + } + + } + +// public static void defineTagsList(ServiceReqDetails service, String[] serviceTags) { +// List<String> taglist = new ArrayList<String>(); +// WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); +// for (String tag : serviceTags) { +// serviceTagsTextbox.clear(); +// serviceTagsTextbox.sendKeys(tag); +// GeneralUIUtils.sleep(1000); +// serviceTagsTextbox.sendKeys(Keys.ENTER); +// taglist.add(tag); +// } +// taglist.add(0, service.getName()); +// service.setTags(taglist); +// } + + public static void defineTagsList2(List<String> serviceTags){ + WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); + for (String tag : serviceTags) { + serviceTagsTextbox.clear(); + serviceTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + serviceTagsTextbox.sendKeys(Keys.ENTER); + } + } + + public static Select defineServiceCategory(String category) { + + return GeneralUIUtils.getSelectList(category, "selectGeneralCategory"); + } + + public static void defineServicePmatt(String pmatt) { + WebElement attPmattTextbox = GeneralUIUtils.getWebElementByTestID("pmatt"); + attPmattTextbox.clear(); + attPmattTextbox.sendKeys(pmatt); + } + + public static void selectRandomResourceIcon() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.ICON); + WebDriverWait wait = new WebDriverWait(driver, 6); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"))); + List<WebElement> iconElement = driver.findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")); + iconElement.get(0).click(); + } + + public static String defineDescription(String description) { + WebElement descriptionTextbox = GeneralUIUtils.getWebElementByTestID("description"); + descriptionTextbox.clear(); + descriptionTextbox.sendKeys(description); + return description; + } + + public static void defineContactId(String userId) { + WebElement attContact = GeneralUIUtils.getWebElementByTestID("attContact"); + attContact.clear(); + attContact.sendKeys(userId); + } + + public static WebElement clickAddArtifact() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking Add Artifact button")); + return GeneralUIUtils.getWebElementByTestID("addArtifactButton"); + } + + public static WebElement getArtifactName() { + return GeneralUIUtils.getWebElementByTestID("artifactName"); + } + + public static WebElement getArtifactDetails() { + return GeneralUIUtils.getWebElementByTestID("artifactDisplayName"); + } + + public static void fillServiceGeneralPage(ServiceReqDetails service, User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Fill in metadata values in general page")); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + defineTagsList2(service.getTags()); + ServiceGeneralPage.defineContactId(service.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createService(ServiceReqDetails service, User user) throws Exception, AWTException { + clickAddService(); + fillServiceGeneralPage(service, user); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("The service %s was created", service.getName())); + } + + public static void setServiceCategory(ServiceReqDetails service, ServiceCategoriesEnum category){ + CategoryDefinition categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(category.getValue()); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(categoryDefinition); + service.setCategories(categories); + } + + public static void createServiceWithDefaultTagAndUserId(ServiceReqDetails service, User user) { + clickAddService(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Defining General Page fields")); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickCreateButton(); + } + + public static void clickAddService(){ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking the Add Service button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Service button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } + +} |