diff options
Diffstat (limited to 'ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities')
18 files changed, 2101 insertions, 4174 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 index 6587bd8f28..57a2bf83dc 100644 --- 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 @@ -20,12 +20,11 @@ package org.openecomp.sdc.ci.tests.utilities; +import com.paulhammant.ngwebdriver.NgWebDriver; 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() { 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 index db621f3355..2ee7e69d60 100644 --- 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 @@ -30,13 +30,8 @@ public class AdminWorkspaceUIUtilies { 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); 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 index 501a7471a5..c3876dc1c9 100644 --- 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 @@ -20,33 +20,11 @@ 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 com.aventstack.extentreports.Status; import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; 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; @@ -55,585 +33,336 @@ import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.Assert; -import com.aventstack.extentreports.Status; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; 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 warning 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 warning 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 warning 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.getLastModifiedFileNameFromDir(); - - 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 file " + expectedFile.getName()); - assertTrue("File " + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size()); - assertTrue("File " + actualFile.getName() + " does not contains all expected parameters", 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 parameters", newMap.entrySet().containsAll(mapExpectedProperties.entrySet())); - } - - - public static File uploadCreatedUpdateParametersEnvFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws Exception { + private static final String PARAMETERS = "parameters"; + private static final String DATA_TESTS_ID = "//*[@data-tests-id='"; + + private ArtifactUIUtils() { + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo) throws Exception { + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + fillAndAddNewArtifactParameters(artifactInfo, artifactPopup); + } + + 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 void validateArtifactNameVersionType(String artifactLabel, String artifactVersion, String artifactType) { + 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 warning represent defect."); + } + if (artifactVersion != null) { + 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 warning represent defect."); + } + } + if (artifactType != null) { + 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 warning represent defect."); + } + } + } + + 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 { + 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 { + 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 { + 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 { + 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.getLastModifiedFileNameFromDir(); + + 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 file " + expectedFile.getName()); + assertTrue("File " + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size()); + assertTrue("File " + actualFile.getName() + " does not contains all expected parameters", 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 parameters", 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"); + 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; -} - + 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) { + 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 deleted file mode 100644 index c53fef596a..0000000000 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/AuditCDUtils.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============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/CatalogUIUtilitis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/CatalogUIUtilitis.java index bf8f1cc3bb..56f0b757b8 100644 --- 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 @@ -20,11 +20,7 @@ package org.openecomp.sdc.ci.tests.utilities; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - +import com.aventstack.extentreports.Status; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum; @@ -35,59 +31,15 @@ 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; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; 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) { @@ -113,29 +65,26 @@ public class CatalogUIUtilitis { return Type; } - public static List<String> catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum) throws Exception { + public static List<String> catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum){ 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(); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); break; case READY_FOR_TESTING: status = Arrays.asList("READY_FOR_CERTIFICATION"); - GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); break; case IN_TESTING: status = Arrays.asList("CERTIFICATION_IN_PROGRESS"); - GeneralUIUtils.getWebElementByTestID(statusEnum.getCatalogValue()).click(); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).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(); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); break; } return status; @@ -148,72 +97,22 @@ public class CatalogUIUtilitis { 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; + public static WebElement clickOnUpperCategoryCheckbox() /*throws InterruptedException*/ { + WebElement categoryCheckbox = getCategoryCheckbox(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s category ...", categoryCheckbox.getText())); + categoryCheckbox.click(); + GeneralUIUtils.ultimateWait(); + return categoryCheckbox; } - @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 WebElement getCategoryCheckbox() { + List<WebElement> categoryCheckboxes = GeneralUIUtils.getElementsByCSS("span[data-tests-id*='category']"); // get all categories and subcategories + return categoryCheckboxes.get(0); } public static void clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle leftPanelElement) throws InterruptedException { 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 index 4b3ee3fc17..b1e8955f3d 100644 --- 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 @@ -20,49 +20,18 @@ package org.openecomp.sdc.ci.tests.utilities; -import java.io.File; -import java.util.List; - +import com.aventstack.extentreports.Status; 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 com.aventstack.extentreports.Status; +import java.util.List; 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 @@ -88,55 +57,8 @@ public class DownloadManager { } - - /*public static void downloadCsarByNameFromVSPRepository(String vspName, String vspId, Boolean isDelete) throws Exception{ - - if(isDelete){ - 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(); - } - }*/ - - public static void downloadCsarByNameFromVSPRepository(String vspName, String vspId) throws Exception{ downloadCsarByNameFromVSPRepository(vspName, true); } -// AttFtpClient instance = AttFtpClient.getInstance(); -// -// String server = "localhost"; -// 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 index a9f6cc5c66..0394513de0 100644 --- 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 @@ -20,29 +20,8 @@ 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.nio.file.Paths; -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 com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; import org.apache.commons.io.FileUtils; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.ci.tests.config.Config; @@ -52,440 +31,456 @@ import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils; import org.openecomp.sdc.common.util.GeneralUtility; import org.yaml.snakeyaml.Yaml; -import com.aventstack.extentreports.Status; -import com.clearspring.analytics.util.Pair; +import java.io.*; +import java.nio.file.Paths; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import static org.testng.AssertJUnit.assertTrue; 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 = new HashMap<>(); - 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 Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception { - @SuppressWarnings("unchecked") - Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath); - return dataTypesMap; - } + // ------------------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 = new HashMap<>(); + 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 Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception { + @SuppressWarnings("unchecked") + Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath); + return dataTypesMap; + } // ------------------------------------------------------------------------------------------------- - - - /** - * @param folder, folder name under "Files" folder - * @return path to given folder from perspective of working directory or sdc-vnfs repository - */ - public static String getFilePath(String folder) { - String filepath = System.getProperty("filePath"); - boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty()); - - // return folder from perspective of sdc-vnfs repository - if (isFilePathEmptyOrNull && ( System.getProperty("os.name").contains("Windows") || System.getProperty("os.name").contains("Mac"))) { - return FileHandling.getResourcesFilesPath() + folder + File.separator; - } - - // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory ) - return FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; - } - - public static String getBasePath() { - return System.getProperty("user.dir") + File.separator; - } - - public static String getSdcVnfsPath() { - return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString(); - } - - 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() { + + + /** + * @param folder, folder name under "Files" folder + * @return path to given folder from perspective of working directory or sdc-vnfs repository + */ + public static String getFilePath(String folder) { + String filepath = System.getProperty("filePath"); + boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty()); + + // return folder from perspective of sdc-vnfs repository + if (isFilePathEmptyOrNull && (System.getProperty("os.name").contains("Windows") || System.getProperty("os.name").contains("Mac"))) { + return FileHandling.getResourcesFilesPath() + folder + File.separator; + } + + // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory ) + return FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getSdcVnfsPath() { + String vnfsPath = System.getProperty("vnfs.path"); + if (vnfsPath != null && !vnfsPath.isEmpty()) { + return vnfsPath; + } + return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString(); + } + + 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; - return getSdcVnfsPath()+ File.separator + "ui-tests" + 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 String getUpdateVSPVnfRepositoryPath() { - return getFilePath("UpdateVSP"); - } - - 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 List<String> filterFileNamesListFromFolder(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()); - } - - filenames.removeAll(OnboardingUtils.exludeVnfList); - - return filenames; - } - - } 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(); - - List<String> artifactNames = new ArrayList<String>(); - - while(entries.hasMoreElements()){ - ZipEntry nextElement = entries.nextElement(); - if (!nextElement.isDirectory()){ - if (!nextElement.getName().equals("MANIFEST.json")){ - String name = nextElement.getName(); - artifactNames.add(name); - } - } - } - zipFile.close(); - // convert list to array - return artifactNames.toArray(new String[0]); - } - 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; - - } + return getSdcVnfsPath() + File.separator + "ui-tests" + 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 String getUpdateVSPVnfRepositoryPath() { + return getFilePath("UpdateVSP"); + } + + 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 List<String> filterFileNamesListFromFolder(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()); + } + + filenames.removeAll(OnboardingUtils.exludeVnfList); + + return filenames; + } + + } 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(); + + List<String> artifactNames = new ArrayList<String>(); + + while (entries.hasMoreElements()) { + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()) { + if (!nextElement.getName().equals("MANIFEST.json")) { + String name = nextElement.getName(); + artifactNames.add(name); + } + } + } + zipFile.close(); + // convert list to array + return artifactNames.toArray(new String[0]); + } 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 List<String> getZipFileNamesFromFolder(String filepath) { - return filterFileNamesListFromFolder(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; - } - - - /** - * @return last modified file name from default directory - * @throws Exception - */ - public static synchronized File getLastModifiedFileNameFromDir() throws Exception{ - return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory()); - } - - /** - * @param dirPath - * @return last modified file name from dirPath directory - */ - public static synchronized File getLastModifiedFileNameFromDir(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.cleanDirectory(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.calculateMD5Base64EncodedByString(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 List<String> getZipFileNamesFromFolder(String filepath) { + return filterFileNamesListFromFolder(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; + } + + + /** + * @return last modified file name from default directory + * @throws Exception + */ + public static synchronized File getLastModifiedFileNameFromDir() throws Exception { + return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory()); + } + + /** + * @param dirPath + * @return last modified file name from dirPath directory + */ + public static synchronized File getLastModifiedFileNameFromDir(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); + if (dir.exists()) { + try { + FileUtils.cleanDirectory(dir); + } catch (IllegalArgumentException e) { + System.out.println("Failed to clean " + dir); + } catch (IOException e) { + System.out.println("Failed to clean " + 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.calculateMD5Base64EncodedByString(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()) { @@ -495,26 +490,26 @@ public class FileHandling { 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 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[] 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; - } + 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(); @@ -535,33 +530,33 @@ public class FileHandling { } bos.close(); } - - public static int getFileCountFromDefaulDownloadDirectory(){ - return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length; + + 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("\"",""); - } + 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 index f198ed98a1..30e68234ba 100644 --- 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 @@ -22,834 +22,696 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; 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.openecomp.sdc.ci.tests.utils.Utils; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.support.ui.*; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; import java.awt.*; 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 static org.testng.AssertJUnit.assertTrue; + 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); - } + private static final String DATA_TESTS_ID = "//*[@data-tests-id='"; + private static final String COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW = "color: yellow; border: 4px solid yellow;"; - 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); - } + private static int timeOut = (int) (60 * 1.5); + public static int getTimeOut() { + return timeOut; + } - 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(); - } - } + /**************** DRIVER ****************/ - 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 WebDriver getDriver() { + try { + return DriverFactory.getDriver(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - 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 boolean isWebElementExistByClass(String className) { - if(getDriver().findElements(By.className(className)).size() == 0) { - return false; - } - return true; - } + public static List<WebElement> getElemenetsFromTable(By by) { + return getDriver().findElements(by); + } - public static WebElement getInputElement(String dataTestId) { - try{ - ultimateWait(); - return getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); - } - catch(Exception e){ - return null; - } - } + 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 List<WebElement> getInputElements(String dataTestId) { - ultimateWait(); - return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + public static File takeScreenshot(String screenshotFilename, String dir) throws IOException { + return takeScreenshot(screenshotFilename, dir, null); + } - } - - - 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 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 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 boolean isWebElementExistByTestId(String dataTestId) { + return getDriver().findElements(By.xpath(DATA_TESTS_ID + dataTestId + "']")).size() != 0; + } - public static void clickOnElementByClassName(String className) { - WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); - wait.until(ExpectedConditions.elementToBeClickable(By.className(className))).click(); - ultimateWait(); - } + public static boolean isWebElementExistByClass(String className) { + return getDriver().findElements(By.className(className)).size() != 0; + } - public static void clickOnElementById(String id) { - WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); - wait.until(ExpectedConditions.elementToBeClickable(By.id(id))).click(); - 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 getInputElement(String dataTestId) { + try { + ultimateWait(); + return getDriver().findElement(By.xpath(DATA_TESTS_ID + dataTestId + "']")); + } catch (Exception e) { + return null; + } + } - 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) { - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to %s page ", stepName.toString())); - moveToStep(stepName.getValue()); - } + 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 WebElement getWebElementByPresence(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.presenceOfElementLocated(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 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); + return wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath(DATA_TESTS_ID + dataTestId + "']")))).isDisplayed(); + } 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 clickOnElementByInputTestIdWithoutWait(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 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); + 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 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(); + } + + public static void sleep(int duration) { + try { + Thread.sleep(duration); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public static void moveToStep(DataTestIdEnum.StepsEnum stepName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to %s page ", stepName.toString())); + moveToStep(stepName.getValue()); + } + + public static void moveToStep(String dataTestId) { + clickOnElementByTestId(dataTestId); + } + + + 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> getElementsByCSS(String cssString) /*throws InterruptedException*/ { + GeneralUIUtils.waitForLoader(); + return getDriver().findElements(By.cssSelector(cssString)); + } + + 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 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(); + return new Select(getDriver().findElement(By.xpath(DATA_TESTS_ID + dataTestId + "']"))).getFirstSelectedOption(); + } + + 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 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); + 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; - } - - - + 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); + ultimateWait(); + 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;"); + 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)); + getDriver().findElement(By.cssSelector(".asdc-app-title")).click(); + } + + 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 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); + if (duration > timeOut) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Delays on page, %d seconds", duration)); + } + } + + 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(); - } - } - + return By.xpath("//*[contains(text(),'" + textInElement + "')]"); + } + + public static WebElement getClickableButtonBy(By by, int timout) { + try { + WebDriverWait wait = new WebDriverWait(getDriver(), timout); + return wait.until(ExpectedConditions.elementToBeClickable(by)); + } 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 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)); - } - + ultimateWait(); + return getDriver().findElement(By.cssSelector(cssString)); + } + public static String getDataTestIdAttributeValue(WebElement element) { - return element.getAttribute("data-tests-id"); - } - + 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; - } - } - + return element.getAttribute("textContent"); + } + 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); - } - - public static boolean checkForDisabledAttributeInHiddenElement(String cssString){ - Object elementAttributes = getAllElementAttributes(getDriver().findElement(By.cssSelector(cssString))); - return elementAttributes.toString().contains("disabled"); - } + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssString))).click(); + ultimateWait(); + } - public static void setTextInElementByDataTestID(String dataTestsID, String text) - { - WebElement webElement = GeneralUIUtils.getWebElementByTestID(dataTestsID); - webElement.clear(); - webElement.sendKeys(text); - ultimateWait(); - } + public static boolean checkForDisabledAttribute(String dataTestId) { + Object elementAttributes = getAllElementAttributes(waitForElementVisibilityByTestId(dataTestId)); + return elementAttributes.toString().contains("disabled"); + } - public static void selectByValueTextContained(String dataTestsId, String value) { + public static void dragAndDropElementByY(WebElement area, int yOffset) { + Actions actions = new Actions(getDriver()); + actions.dragAndDropBy(area, 10, yOffset).perform(); + ultimateWait(); + } - List<WebElement> options = GeneralUIUtils.getWebElementsListBy(By.xpath(String.format("//select[@data-tests-id='%s']//option[contains(@value,'%s')]",dataTestsId,value))); + public static void waitForBackLoader() { + waitForBackLoader(timeOut); + } - boolean matched = false; - for (WebElement option : options) { - option.click(); - matched = true; - } + public static void waitForBackLoader(int timeOut) { + sleep(100); + waitForElementInVisibilityBy(By.className("tlv-loader-back"), timeOut); + } - if (!matched) { - throw new NoSuchElementException("Cannot locate option with value: " + value); - } + public static void addStringtoClipboard(String text) { + StringSelection selection = new StringSelection(text); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(selection, selection); + } - ultimateWait(); - } + public static boolean checkForDisabledAttributeInHiddenElement(String cssString) { + boolean isDisabled = false; + for (int i = 0; i < 3; i++) { + Object elementAttributes = getAllElementAttributes(getWebElementByPresence(By.cssSelector(cssString), timeOut)); + isDisabled = elementAttributes.toString().contains("disabled"); + if (isDisabled) + break; + ultimateWait(); + } + return isDisabled; + } - public static void setTextInElementByXpath(String xPath, String text) - { - WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath)); - webElement.clear(); - webElement.click(); - webElement.sendKeys(text); - ultimateWait(); - } + public static void selectByValueTextContained(String dataTestsId, String value) { - public static String getTextValueFromInput(WebElement webElement) - { - return webElement.getAttribute("value"); - } + List<WebElement> options = GeneralUIUtils.getWebElementsListBy(By.xpath(String.format("//select[@data-tests-id='%s']//option[contains(@value,'%s')]", dataTestsId, value))); - public static String getTextValueFromWebElementByXpath(String Xpath) - { - WebElement webElement = getWebElementBy(By.xpath(Xpath)); - return webElement.getAttribute("value"); - } - - public static void refreshPage(){ - Actions actions = new Actions(getDriver()); - actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform(); - } + boolean matched = false; + for (WebElement option : options) { + option.click(); + matched = true; + } + + if (!matched) { + throw new NoSuchElementException("Cannot locate option with value: " + value); + } + + ultimateWait(); + } + + public static void setTextInElementByXpath(String xPath, String text) { + WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath)); + webElement.clear(); + webElement.click(); + webElement.sendKeys(text); + ultimateWait(); + } + public static void clickOnElementByXpath(String xPath) { + WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath)); + webElement.click(); + ultimateWait(); + } + + public static String getTextValueFromWebElementByXpath(String Xpath) { + WebElement webElement = getWebElementBy(By.xpath(Xpath)); + return webElement.getAttribute("value"); + } + + public static List<WebElement> findElementsByXpath(String xPath) { + return getDriver().findElements(By.xpath(xPath)); + } + public static void clickOnBrowserBackButton() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Going to press on back browser button."); + getDriver().navigate().back(); + ultimateWait(); + } + + public static String copyCurrentURL() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Copying current URL"); + return getDriver().getCurrentUrl(); + } + + public static void navigateToURL(String url) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Navigating to URL " + url); + getDriver().navigate().to(url); + } - + public static Object getElementPositionOnCanvas(String elementName) { + String scriptJS = "var cy = window.jQuery('.sdc-composition-graph-wrapper').cytoscape('get');\n" + + "var n = cy.nodes('[name=\"" + elementName + "\"]');\n" + + "var nPos = n.renderedPosition();\n" + + "return JSON.stringify({\n" + + "\tx: nPos.x,\n" + + "\ty: nPos.y\n" + + "})"; + return ((JavascriptExecutor) getDriver()).executeScript(scriptJS); + } + + public static Object getElementGreenDotPositionOnCanvas(String elementName) { + String scriptJS = "var cy = window.jQuery('.sdc-composition-graph-wrapper').cytoscape('get');\n" + + "var cyZoom = cy.zoom();\n" + + "var n = cy.nodes('[name=\"" + elementName + "\"]');\n" + + "var nPos = n.renderedPosition();\n" + + "var nData = n.data();\n" + + "var nImgSize = nData.imgWidth;\n" + + "var shiftSize = (nImgSize-18)*cyZoom/2;\n" + + "return JSON.stringify({\n" + + "\tx: nPos.x + shiftSize,\n" + + "\ty: nPos.y - shiftSize\n" + + "});"; + return ((JavascriptExecutor) getDriver()).executeScript(scriptJS); + } + + public static Long getAndValidateActionDuration (Runnable action, int regularTestRunTime){ + Long actualTestRunTime = null; + try { + actualTestRunTime = Utils.getActionDuration(() -> { + try { + action.run(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + double factor = 1.5; + + assertTrue("Expected test run time should be less than " + regularTestRunTime*factor + ", " + + "actual time is " + actualTestRunTime , regularTestRunTime*factor>actualTestRunTime); +// SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + actualTestRunTime + " seconds"); + return actualTestRunTime; + } } 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 index b40ebf86fc..512e63a4ee 100644 --- 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 @@ -1,138 +1,102 @@ -/*- - * ============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 com.aventstack.extentreports.Status; -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 java.util.List; - -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); - } - } - - public static void findComponentAndClickByVersion(String componentName, String version) throws Exception { - SetupCDTest.getExtendTest().log(Status.INFO, String.format("finding component %s v%s", componentName, version)); - GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName); - List<WebElement> foundComp = null; - try { - foundComp = GeneralUIUtils.getWebElementsListByTestID(componentName + "Version"); - - for (WebElement webElement : foundComp) - { - if(webElement.getText().contains(version)) - { - webElement.click(); - GeneralUIUtils.ultimateWait(); - break; - } - } - } 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); - } - } -} +/*-
+ * ============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 com.aventstack.extentreports.Status;
+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 java.util.List;
+
+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:
+ 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 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);
+ }
+ }
+
+ public static void findComponentAndClickByVersion(String componentName, String version) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("finding component %s v%s", componentName, version));
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName);
+ List<WebElement> foundComp = null;
+ try {
+ foundComp = GeneralUIUtils.getWebElementsListByTestID(componentName + "Version");
+
+ for (WebElement webElement : foundComp) {
+ if (webElement.getText().contains(version)) {
+ webElement.click();
+ GeneralUIUtils.ultimateWait();
+ break;
+ }
+ }
+ } 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 deleted file mode 100644 index d1045eab76..0000000000 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ImportAssetUIUtils.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============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/OnboardingUiUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java index e2956774bf..9ef9515db3 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java @@ -21,13 +21,13 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; -import com.clearspring.analytics.util.Pair; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.datatypes.*; 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.pages.DeploymentArtifactPage; +import org.openecomp.sdc.ci.tests.pages.GeneralPageElements; import org.openecomp.sdc.ci.tests.pages.HomePage; import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage; import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils; @@ -45,136 +45,147 @@ import java.util.stream.Collectors; public class OnboardingUiUtils { - private static void importUpdateVSP(Pair<String, VendorSoftwareProductObject> vsp, boolean isUpdate) throws Exception{ - String vspName = vsp.left; - VendorSoftwareProductObject 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, VendorSoftwareProductObject> vsp) throws Exception{ - ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); - importUpdateVSP(vsp, true); - } - - public static void importVSP(Pair<String, VendorSoftwareProductObject> vsp) throws Exception{ - ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); - importUpdateVSP(vsp, false); - } - - public static void updateVnfAndValidate(String filePath, Pair<String, VendorSoftwareProductObject> 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)); - - VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vsp.right, user, filePath, updatedVnfFile); - HomePage.showVspRepository(); - updateVSP(vsp); - ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); - DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, updatedVnfFile); - } - - public static Pair<String, VendorSoftwareProductObject> onboardAndValidate(ResourceReqDetails resourceReqDetails, 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)); - - AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user); - Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers); - String vspName = createVendorSoftwareProduct.left; - - DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.getVspId()); - File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); - - 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); - - List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). - map(e -> e.getFileName()). - collect(Collectors.toList()); - - validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); - - DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); - return createVendorSoftwareProduct; - } - - public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts, - List<String> heatEnvFilesFromCSAR) { - String artifactVersion; - String artifactName; - - for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { - artifactVersion = "1"; - - if(deploymentArtifact.getType().equals("HEAT_ENV")) { - continue; - } else if(deploymentArtifact.getFileName().contains(".")) { - artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")); - } else { - artifactName = deploymentArtifact.getFileName().trim(); - } - - if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){ - artifactVersion = "2"; - } - ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); - } - } + private static void importUpdateVSP(VendorSoftwareProductObject vsp, boolean isUpdate, boolean restore) throws Exception { + String vspName = vsp.getName(); + boolean vspFound = HomePage.searchForVSP(vspName); + + if (vspFound) { + List<WebElement> elementsFromTable = HomePage.getElemenetsFromTable(); + elementsFromTable.get(1).click(); + GeneralUIUtils.waitForLoader(); + + if (isUpdate) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + } else { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + } + if (restore) { + GeneralPageElements.restoreComponentFromElementPage(vspName); + } + doCheckOut(); + //Metadata verification + onboardedVnfMetadataVerification(vsp, isUpdate); + 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 onboardedVnfMetadataVerification(VendorSoftwareProductObject vsp, boolean isUpdate) { + if (isUpdate) { + VfVerificator.verifyOnboardedVnfMetadataAfterUpdateVNF(vsp.getName(), vsp); + } else { + VfVerificator.verifyOnboardedVnfMetadata(vsp.getName(), vsp); + } + } + + public static void doCheckOut() { + 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(); + } + } + + private static void waitUntilVnfCreated() { + ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(60 * 10); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void updateVSP(VendorSoftwareProductObject vsp, boolean restore) throws Exception { + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.getName()); + importUpdateVSP(vsp, true, restore); + } + + public static void updateVSP(VendorSoftwareProductObject vsp) throws Exception { + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.getName()); + importUpdateVSP(vsp, true, false); + } + + public static void importVSP(VendorSoftwareProductObject vsp) throws Exception { + ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.getName()); + importUpdateVSP(vsp, false, false); + } + + public static void updateVnfAndValidate(String filePath, VendorSoftwareProductObject vsp, String updatedVnfFile, User user) throws 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)); + + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vsp, user, filePath, updatedVnfFile); + HomePage.showVspRepository(); + updateVSP(vsp); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, updatedVnfFile); + } + + + public static VendorSoftwareProductObject onboardAndValidate(ResourceReqDetails resourceReqDetails, 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)); + + AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user); + VendorSoftwareProductObject createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers); + String vspName = createVendorSoftwareProduct.getName(); + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.getVspId()); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + + 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); + + List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). + map(e -> e.getFileName()). + collect(Collectors.toList()); + + validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + return createVendorSoftwareProduct; + } + + public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts, + List<String> heatEnvFilesFromCSAR) { + String artifactVersion; + String artifactName; + + for (HeatMetaFirstLevelDefinition deploymentArtifact : deploymentArtifacts) { + artifactVersion = "1"; + + if (deploymentArtifact.getType().equals("HEAT_ENV")) { + continue; + } else if (deploymentArtifact.getFileName().contains(".")) { + artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")); + } else { + artifactName = deploymentArtifact.getFileName().trim(); + } + + if (heatEnvFilesFromCSAR.contains(artifactName + ".env")) { + artifactVersion = "2"; + } + ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); + } + } } diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtillViaApis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtillViaApis.java deleted file mode 100644 index 8a319a3af4..0000000000 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtillViaApis.java +++ /dev/null @@ -1,240 +0,0 @@ -/*- - * ============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; - -public class OnboardingUtillViaApis { - -// 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; -// } - -// public static Pair<String, VendorSoftwareProductObject> createVspViaApis(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile, User user, Boolean skipReport) throws Exception { -// -// VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); -// -// AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(user); -// Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUiUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers); -// Map<String, String> map = createVendorSoftwareProduct.right; -// vendorSoftwareProductObject.setAttContact(map.get("attContact")); -// vendorSoftwareProductObject.setCategory(map.get("category")); -// vendorSoftwareProductObject.setComponentId(map.get("componentId")); -// vendorSoftwareProductObject.setDescription(map.get("description")); -// vendorSoftwareProductObject.setSubCategory(map.get("subCategory")); -// vendorSoftwareProductObject.setVendorName(map.get("vendorName")); -// vendorSoftwareProductObject.setVspId(map.get("vspId")); -// Pair<String, VendorSoftwareProductObject> pair = new Pair<String, VendorSoftwareProductObject>(createVendorSoftwareProduct.left, vendorSoftwareProductObject); -// return pair; -// } - -/* public static Resource createResourceFromVSP(Pair<String, Map<String, String>> createVendorSoftwareProduct, String vspName) throws Exception { - List<String> tags = new ArrayList<>(); - tags.add(vspName); - Map<String, String> map = createVendorSoftwareProduct.right; - ResourceReqDetails resourceDetails = new ResourceReqDetails(); - resourceDetails.setCsarUUID(map.get("vspId")); - resourceDetails.setCsarVersion("1.0"); - resourceDetails.setName(vspName); - resourceDetails.setTags(tags); - resourceDetails.setDescription(map.get("description")); - resourceDetails.setResourceType(map.get("componentType")); - resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); - resourceDetails.setVendorName(map.get("vendorName")); - resourceDetails.setVendorRelease("1.0"); - resourceDetails.setResourceType("VF"); - resourceDetails.setResourceVendorModelNumber("666"); - resourceDetails.setContactId(map.get("attContact")); - resourceDetails.setIcon("defaulticon"); - Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value(); - - return resource; - }*/ - -// public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails) throws Exception { -// Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value(); -// return resource; -// } - -// public static void downloadToscaCsarToDirectory(Component component, File file) { -// try { -// Either<String, RestResponse> componentToscaArtifactPayload = AtomicOperationUtils.getComponenetArtifactPayload(component, "assettoscacsar"); -// if(componentToscaArtifactPayload.left().value() != null){ -// convertPayloadToFile(componentToscaArtifactPayload.left().value(), file); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } - -// public static void convertPayloadToFile(String payload, File file, boolean isBased64, boolean isSdcFormat) throws IOException{ -// -// Gson gson = new Gson(); -// byte[] byteArray = null; -// Map<String, String> fromJson; -// @SuppressWarnings("unchecked") -// String string = null;// = fromJson.get("base64Contents").toString(); -// if(isSdcFormat){ -// fromJson = gson.fromJson(payload, Map.class); -// string = fromJson.get("base64Contents").toString(); -// }else if (isBased64) { -// byteArray = Base64.decode(string.getBytes(StandardCharsets.UTF_8)); -// }else{ -// byteArray = payload.getBytes(StandardCharsets.UTF_8); -// } -// File downloadedFile = new File(file.getAbsolutePath()); -// FileOutputStream fos = new FileOutputStream(downloadedFile); -// fos.write(byteArray); -// fos.flush(); -// fos.close(); -// -// } - -// public static void convertPayloadToFile(String payload, File file) throws IOException{ -// -// Gson gson = new Gson(); -// @SuppressWarnings("unchecked") -// Map<String, String> fromJson = gson.fromJson(payload, Map.class); -// String string = fromJson.get("base64Contents").toString(); -// byte[] byteArray = Base64.decode(string.getBytes(StandardCharsets.UTF_8)); -// File downloadedFile = new File(file.getAbsolutePath()); -// FileOutputStream fos = new FileOutputStream(downloadedFile); -// fos.write(byteArray); -// fos.flush(); -// fos.close(); -// } - - -// public static void convertPayloadToZipFile(String payload, File file) throws IOException{ -// -// byte[] byteArray = payload.getBytes(StandardCharsets.ISO_8859_1); -// File downloadedFile = new File(file.getAbsolutePath()); -// FileOutputStream fos = new FileOutputStream(downloadedFile); -// fos.write(byteArray); -// fos.flush(); -// fos.close(); -// -// -//// ZipOutputStream fos = null; -//// -//// -//// for (Charset charset : Charset.availableCharsets().values()) { -//// try{ -//// // System.out.println("How to do it???"); -//// File downloadedFile = new File(file.getAbsolutePath() + "_" + charset +".csar"); -//// fos = new ZipOutputStream(new FileOutputStream(downloadedFile)); -//// byte[] byteArray = payload.getBytes(charset); -//// fos.write(byteArray); -//// fos.flush(); -//// -//// } -//// catch(Exception e){ -//// fos.close(); -//// } -//// } -// System.out.println(""); -// -//// ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(byteArray)); -//// ZipEntry entry = null; -//// while ((entry = zipStream.getNextEntry()) != null) { -//// -//// String entryName = entry.getName(); -//// -//// FileOutputStream out = new FileOutputStream(file+"/"+entryName); -//// -//// byte[] byteBuff = new byte[4096]; -//// int bytesRead = 0; -//// while ((bytesRead = zipStream.read(byteBuff)) != -1) -//// { -//// out.write(byteBuff, 0, bytesRead); -//// } -//// -//// out.close(); -//// zipStream.closeEntry(); -//// } -//// zipStream.close(); -//// -// -// -// -// BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(payload.getBytes(StandardCharsets.ISO_8859_1))); -// String filePath = file.toString(); -// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); -// int inByte; -// while((inByte = bis.read()) != -1) bos.write(inByte); -// bis.close(); -// bos.close(); -// } - -// public static Either<String, RestResponse> getVendorSoftwareProduct(String vspId, User user, Boolean validateState) throws Exception { -// -// Config config = Utils.getConfig(); -// String url = String.format(Urls.GET_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), vspId); -// String userId = user.getUserId(); -// Map<String, String> headersMap = prepareHeadersMap(userId); -// headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), "123456"); -// headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "*/*"); -// headersMap.put("Accept-Encoding", "gzip, deflate, br"); -// HttpRequest http = new HttpRequest(); -// RestResponse response = http.httpSendGet(url, headersMap); -// if (validateState) { -// assertTrue("add property to resource failed: " + response.getResponseMessage(), response.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); -// } -// if (response.getErrorCode() != BaseRestUtils.STATUS_CODE_SUCCESS && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) { -// return Either.right(response); -// } -// return Either.left(response.getResponse()); -// -// } - -// public static ResourceReqDetails prepareOnboardedResourceDetailsBeforeCreate(ResourceReqDetails resourceDetails, VendorSoftwareProductObject vendorSoftwareProductObject) { -// -// List<String> tags = new ArrayList<>(); -// tags.add(vendorSoftwareProductObject.getName()); -//// ResourceReqDetails resourceDetails = new ResourceReqDetails(); -// resourceDetails.setCsarUUID(vendorSoftwareProductObject.getVspId()); -// resourceDetails.setCsarVersion(vendorSoftwareProductObject.getVersion()); -// resourceDetails.setName(vendorSoftwareProductObject.getName()); -// resourceDetails.setTags(tags); -// resourceDetails.setDescription(vendorSoftwareProductObject.getDescription()); -//// resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); -// resourceDetails.setVendorName(vendorSoftwareProductObject.getVendorName()); -//// resourceDetails.setVendorRelease("1.0"); -// resourceDetails.setResourceType("VF"); -// resourceDetails.setResourceVendorModelNumber("666"); -// resourceDetails.setContactId(vendorSoftwareProductObject.getAttContact()); -//// resourceDetails.setIcon("defaulticon"); -// -// return resourceDetails; -// } - - /*public static ServiceReqDetails prepareServiceDetailsBeforeCreate(ServiceReqDetails serviceDetails, User user) { - - serviceDetails.setServiceType("MyServiceType"); - serviceDetails.setServiceRole("MyServiceRole"); - serviceDetails.setNamingPolicy("MyServiceNamingPolicy"); - serviceDetails.setEcompGeneratedNaming(true); - - return serviceDetails; - }*/ -} diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java index 404325190e..51c5c307af 100644 --- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java +++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java @@ -1,132 +1,135 @@ -package org.openecomp.sdc.ci.tests.utilities; - -import com.aventstack.extentreports.Status; -import com.clearspring.analytics.util.Pair; -import fj.data.Either; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.*; -import org.openecomp.sdc.ci.tests.datatypes.*; -import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize; -import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; -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.SetupCDTest; -import org.openecomp.sdc.ci.tests.pages.CompositionPage; -import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage; -import org.openecomp.sdc.ci.tests.utils.general.*; -import org.openecomp.sdc.ci.tests.utils.general.FileHandling; -import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis; -import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils; - -import java.util.List; - -public class PortMirroringUtils { - - - public static ServiceContainer createServiceFromHeatFile(String filePath, String vnfFile) throws Throwable { -// 1. Import VSP v1.0 - User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName())); - ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile)); - Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers); -// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct); - VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right; -// 2. Create VF, certify - v1.0 is created - resourceReqDetails = org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); - Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); - resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the VF")); -// 3. Create Service add to it the certified VF and certify the Service v1.0 - ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); - Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); - Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); - ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); - service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the Service")); - - return new ServiceContainer(service, resource, vendorSoftwareProductObject, amdocsLicenseMembers); - } - - public static Resource GeneratePNFAndUpdateInput(String resourceName, String vendorModelNumber, User user) throws Exception { - Resource resource = getResourceByType(ResourceTypeEnum.PNF, resourceName, vendorModelNumber); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating pnf %s and certify it", resource.getName())); - Component componentObject = AtomicOperationUtils.getComponentObject(resource, UserRoleEnum.DESIGNER); - UpdateResourceInputViaAPI(user, componentObject, "physicalProbe", "nf_role"); - resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); - return resource; - } - - private static void UpdateResourceInputViaAPI(User user, Component componentObject, String defaultValue, String inputName) throws Exception { - List<InputDefinition> componentInputs = componentObject.getInputs(); - PropertyObject propertyObject = new PropertyObject(defaultValue, inputName, componentInputs.get(1).getParentUniqueId(), componentInputs.get(1).getUniqueId()); - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Update input %s to %s", "nf_role", "physicalProbe")); - PropertyRestUtils.updateInput(componentObject, propertyObject, user); - } - - public static Resource getResourceByType(ResourceTypeEnum resourceTypeEnum, String resourceName, String vendorModelNumber) { - ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(resourceTypeEnum, resourceName, ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, resourceName, vendorModelNumber); - return AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); - } - - public static String createProxyInstanceServiceName(String serviceName, String instanceId) { - String serviceProxyInstanceName = String.format("%s_proxy %s", serviceName, instanceId); - return serviceProxyInstanceName; - } - - public static PortMirrioringConfigurationObject createPortMirriongConfigurationStructure() throws Throwable { - - //Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe - String filePath = FileHandling.getPortMirroringRepositoryPath(); - ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VMME_ZIP.getValue()); - ServiceContainer serviceContainerVprobe_Collector = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VPROBE_ZIP.getValue()); - -// String vmmeSourceName = "ciServiceb560327d162f"; -// String vprobeSourceName = "ciService3d9933d31791"; - - // create service - ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); - //ServiceUIUtils.createService(serviceMetadata, getUser()); - - SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating container %s: ", serviceReqDetails.getName())); - Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); - - String vmmeSourceName = serviceContainerVmme_Source.getService().getName(); - String vprobeSourceName = serviceContainerVprobe_Collector.getService().getName(); - - CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); - GeneralUIUtils.findComponentAndClick(service.getName()); - - ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); - CanvasManager canvasManager = CanvasManager.getCanvasManager(); - - CompositionPage.searchForElement(vmmeSourceName); - CanvasElement serviceElementVmmeSourceName = canvasManager.createElementOnCanvas(vmmeSourceName); - - CompositionPage.searchForElement(vprobeSourceName); - CanvasElement serviceElementVprobeCollector = canvasManager.createElementOnCanvas(vprobeSourceName); - - CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); - CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); - - ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "", - PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue()); - ConnectionWizardPopUpObject connectionWizardPopUpObjectVProbe = new ConnectionWizardPopUpObject("", "", - PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_COLLECTOR_CAP.getValue()); - - canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME); - canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVprobeCollector, CircleSize.SERVICE, portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVProbe); - - PortMirrioringConfigurationObject portMirrioringConfigurationObject = new PortMirrioringConfigurationObject(serviceReqDetails, vmmeSourceName, - vprobeSourceName, canvasManager, serviceElementVmmeSourceName, serviceElementVprobeCollector, service, - portMirroringConfigurationElement, serviceContainerVmme_Source.getService(), serviceContainerVprobe_Collector.getService()); - - return portMirrioringConfigurationObject; - } - -} +package org.openecomp.sdc.ci.tests.utilities;
+
+import com.aventstack.extentreports.Status;
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.ci.tests.datatypes.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+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.SetupCDTest;
+import org.openecomp.sdc.ci.tests.pages.CompositionPage;
+import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage;
+import org.openecomp.sdc.ci.tests.utils.general.*;
+import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
+import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
+
+import java.util.List;
+import java.util.Map;
+
+public class PortMirroringUtils {
+
+
+ public static ServiceContainer createServiceFromHeatFile(String filePath, String vnfFile) throws Throwable {
+// 1. Import VSP v1.0
+ User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile));
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
+// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+// 2. Create VF, certify - v1.0 is created
+ resourceReqDetails = org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
+ Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName()));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the VF"));
+// 3. Create Service add to it the certified VF and certify the Service v1.0
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName()));
+ Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+ ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the Service"));
+
+ return new ServiceContainer(service, resource, vendorSoftwareProductObject, amdocsLicenseMembers);
+ }
+
+ public static Resource GeneratePNFAndUpdateInput(String resourceName, String vendorModelNumber, User user) throws Exception {
+ Resource resource = getResourceByType(ResourceTypeEnum.PNF, resourceName, vendorModelNumber);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating pnf %s and certify it", resource.getName()));
+ Component componentObject = AtomicOperationUtils.getComponentObject(resource, UserRoleEnum.DESIGNER);
+ UpdateResourceInputViaAPI(user, componentObject, "physicalProbe", "nf_role");
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ return resource;
+ }
+
+ private static void UpdateResourceInputViaAPI(User user, Component componentObject, String defaultValue, String inputName) throws Exception {
+ List<InputDefinition> componentInputs = componentObject.getInputs();
+ PropertyObject propertyObject = new PropertyObject(defaultValue, inputName, componentInputs.get(1).getParentUniqueId(), componentInputs.get(1).getUniqueId());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Update input %s to %s", "nf_role", "physicalProbe"));
+ PropertyRestUtils.updateInput(componentObject, propertyObject, user);
+ }
+
+ public static Resource getResourceByType(ResourceTypeEnum resourceTypeEnum, String resourceName, String vendorModelNumber) {
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(resourceTypeEnum, resourceName, ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, resourceName, vendorModelNumber);
+ return AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+ }
+
+ public static String createProxyInstanceServiceName(String serviceName, String instanceId) {
+ String serviceProxyInstanceName = String.format("%s_proxy %s", serviceName, instanceId);
+ return serviceProxyInstanceName;
+ }
+
+ public static PortMirrioringConfigurationObject createPortMirriongConfigurationStructure(boolean isCapPropAssign) throws Throwable {
+
+ //Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe
+ String filePath = FileHandling.getPortMirroringRepositoryPath();
+ ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VMME_ZIP.getValue());
+ ServiceContainer serviceContainerVprobe_Collector = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VPROBE_ZIP.getValue());
+
+ // create service
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ //ServiceUIUtils.createService(serviceMetadata, getUser());
+
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating container %s: ", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ String vmmeSourceName = serviceContainerVmme_Source.getService().getName();
+ String vprobeSourceName = serviceContainerVprobe_Collector.getService().getName();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CanvasElement serviceElementVmmeSourceName = canvasManager.createElementOnCanvas(vmmeSourceName);
+
+ CanvasElement serviceElementVprobeCollector = canvasManager.createElementOnCanvas(vprobeSourceName);
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue());
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVProbe = new ConnectionWizardPopUpObject("", "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_COLLECTOR_CAP.getValue());
+ Map<String, String> capPropValues1 = null;
+
+ if(isCapPropAssign){
+ capPropValues1 = canvasManager.linkElementsWithCapPropAssignment(serviceElementVmmeSourceName, portMirroringConfigurationElement, connectionWizardPopUpObjectVMME);
+ GeneralUIUtils.waitForLoader(2000);
+ canvasManager.linkElementsWithCapPropAssignment(serviceElementVprobeCollector, portMirroringConfigurationElement, connectionWizardPopUpObjectVProbe);}
+ else {
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationElement, connectionWizardPopUpObjectVMME);
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVprobeCollector, portMirroringConfigurationElement, connectionWizardPopUpObjectVProbe);
+ }
+
+
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = new PortMirrioringConfigurationObject(serviceReqDetails, vmmeSourceName,
+ vprobeSourceName, canvasManager, serviceElementVmmeSourceName, serviceElementVprobeCollector, service,
+ portMirroringConfigurationElement, serviceContainerVmme_Source.getService(), serviceContainerVprobe_Collector.getService());
+
+ if(capPropValues1!=null)
+ portMirrioringConfigurationObject.setCapPropValues(capPropValues1);
+
+ return portMirrioringConfigurationObject;
+ }
+
+}
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 index 9e478c8523..bde3340c6e 100644 --- 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 @@ -20,9 +20,7 @@ package org.openecomp.sdc.ci.tests.utilities; -import java.awt.AWTException; -import java.util.List; - +import com.aventstack.extentreports.Status; import org.junit.rules.TestName; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum; @@ -34,7 +32,8 @@ import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; -import com.aventstack.extentreports.Status; +import java.awt.*; +import java.util.List; /** * @author al714h 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 index b1682b34e6..7eb4e63ab3 100644 --- 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 @@ -20,28 +20,17 @@ package org.openecomp.sdc.ci.tests.utilities; -import java.util.HashMap; -import java.util.Map; - +import com.aventstack.extentreports.Status; 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; +import java.util.HashMap; +import java.util.Map; 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>(); @@ -52,7 +41,6 @@ public class PropertiesUIUtils { GeneralUIUtils.setWebElementByTestId("description","description"); Thread.sleep(2000); GeneralUIUtils.getWebElementByTestID("Add").click(); - ; } else if (itemType == "list" || itemType == "map") { GeneralUIUtils.getSelectList(schemaType, "schemaType"); } @@ -60,7 +48,6 @@ public class PropertiesUIUtils { ResourceUIUtils.defineDefaultValueByType(defaultValue); GeneralUIUtils.setWebElementByTestId("description", "des"); GeneralUIUtils.getWebElementByTestID("Add").click(); - ; Thread.sleep(2000); } propertyvalues.put("type", itemType); 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 index 1ce5455dab..916b58a834 100644 --- 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 @@ -20,32 +20,17 @@ 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.event.KeyEvent; -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - +import com.aventstack.extentreports.Status; 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; @@ -57,9 +42,10 @@ 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; +import java.io.File; +import java.util.List; +import java.util.Random; public final class ResourceUIUtils { public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-"; @@ -73,36 +59,6 @@ public final class 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 { @@ -110,33 +66,6 @@ public final class ResourceUIUtils { 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(); @@ -145,19 +74,6 @@ public final class ResourceUIUtils { 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")); @@ -174,51 +90,6 @@ public final class ResourceUIUtils { 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")); @@ -233,61 +104,6 @@ public final class ResourceUIUtils { 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()); @@ -313,11 +129,6 @@ public final class ResourceUIUtils { 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(); } @@ -333,209 +144,6 @@ public final class ResourceUIUtils { 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; - } - /** * @deprecated Use {@link #createVF(ResourceReqDetails,User)} instead */ @@ -549,7 +157,7 @@ public final class ResourceUIUtils { } public static void createResource(ResourceReqDetails resource, User user, DataTestIdEnum.Dashboard button) { - WebElement addVFButton = null; + WebElement addVFButton; try { GeneralUIUtils.ultimateWait(); try{ @@ -585,209 +193,6 @@ public final class ResourceUIUtils { 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. * @@ -808,55 +213,6 @@ public final class ResourceUIUtils { } /** - * 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 @@ -983,141 +339,6 @@ public final class ResourceUIUtils { 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)); @@ -1150,7 +371,25 @@ public final class ResourceUIUtils { } public static void createPNF(ResourceReqDetails resource, User user) throws Exception { - ExtentTestActions.log(Status.INFO, "Going to create a new PNF."); + ExtentTestActions.log(Status.INFO, "Going to create a new PNF"); createResource(resource, user, DataTestIdEnum.Dashboard.BUTTON_ADD_PNF); } + + public static void createCR(ResourceReqDetails resource, User user) throws Exception { + ExtentTestActions.log(Status.INFO, "Going to create a new CR"); + createResource(resource, user, DataTestIdEnum.Dashboard.BUTTON_ADD_CR); + } + + 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); + + } + + } 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 index 0f6999c28f..7ce9fbe90f 100644 --- 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 @@ -21,16 +21,13 @@ package org.openecomp.sdc.ci.tests.utilities; import com.aventstack.extentreports.Status; -import com.fasterxml.jackson.databind.ObjectMapper; 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; @@ -38,308 +35,172 @@ 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 org.openecomp.sdc.ci.tests.utils.rest.*; 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 static org.testng.AssertJUnit.assertTrue; - 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(ElementFactory.getProductPrefix())). - 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(ElementFactory.getServicePrefix())). - 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(ElementFactory.getResourcePrefix())). - 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); - } + 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 resourceUniqueId = resource.getUniqueId(); + if (resourceUniqueId != null) { + getResourceResponse = ResourceRestUtils.getResource(resourceUniqueId); + 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) { + 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 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()); + return ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse()); + } + + public static Map<String, List<CategoryDefinition>> getCategories() throws Exception { + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + Map<String, List<CategoryDefinition>> map = new HashMap<>(); + + + 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("resources"); + List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith(ElementFactory.getResourcePrefix())). + map(e -> e.getUniqueId()). + collect(Collectors.toList()); + for (String uId : collect) { + ResourceRestUtils.markResourceToDelete(uId, userId); + + } + ResourceRestUtils.deleteMarkedResources(userId); + + resourcesArrayList = map.get("services"); + collect = resourcesArrayList.stream(). + filter(e -> e != null). + filter(e -> e.getName() != null). + filter(s -> s.getName().startsWith(ElementFactory.getServicePrefix())). + filter(e -> e.getUniqueId() != null). + map(e -> e.getUniqueId()). + collect(Collectors.toList()); + for (String uId : collect) { + ServiceRestUtils.markServiceToDelete(uId, userId); + } + ServiceRestUtils.deleteMarkedServices(userId); + + } + + 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("According to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ..."); + } + } } 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 index 8b07e621d9..f19b43069e 100644 --- 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 @@ -20,267 +20,93 @@ 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 com.aventstack.extentreports.Status; 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; +import java.util.ArrayList; +import java.util.List; 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(); - } - } + protected static WebDriver driver; + + public ServiceUIUtils(TestName name, String className) { + super(); + } + + 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 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 { + 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()); + ServiceGeneralPage.defineInstantiationType(service.getInstantiationType()); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, "Done creating service over the UI, " + + "about to move into Tosca Artifacts section."); + } + + 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(); + } + } } |