Skip to content

Instantly share code, notes, and snippets.

@naelabdeljawad
Created January 29, 2021 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naelabdeljawad/5e1af8fd7f4c783c8e460182daf8871f to your computer and use it in GitHub Desktop.
Save naelabdeljawad/5e1af8fd7f4c783c8e460182daf8871f to your computer and use it in GitHub Desktop.
Appium Utilities
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.Activity;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.Connection;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
public class AppiumUtilities {
public enum DeviceActions {
BACK, HOME, APPS, ENTER, LANGUAGE, MY_FILES, NOTIFICATIONS, back, home, apps, enter, language, my_files, notifications
}
/**
* clickOnPhone
* @param action
* @return
*/
@SuppressWarnings("rawtypes")
public boolean clickOnPhone(DeviceActions action) {
appiumDriver = new Driver().getAppiumDriver();
switch (action) {
case BACK:
case back:
((AndroidDriver) appiumDriver).pressKeyCode(4);
return true;
case HOME:
case home:
((AndroidDriver) appiumDriver).pressKeyCode(3);
return true;
case APPS:
case apps:
((AndroidDriver) appiumDriver).pressKeyCode(187);
return true;
case ENTER:
case enter:
((AndroidDriver) appiumDriver).pressKeyCode(66);
return true;
case LANGUAGE:
case language:
((AndroidDriver) appiumDriver)
.startActivity(new Activity("com.android.settings", "com.android.settings.LanguageSettings"));
return true;
case MY_FILES:
case my_files:
((AndroidDriver) appiumDriver).startActivity(
new Activity("com.sec.android.app.myfiles", "com.sec.android.app.myfiles.common.MainActivity"));
return true;
case NOTIFICATIONS:
case notifications:
((AndroidDriver) appiumDriver).openNotifications();
return true;
}
return false;
}
/**
* scrollTo
*
* @param text
*/
public void scrollTo(String text) {
try {
appiumDriver = new Driver().getAppiumDriver();
WebElement element = ((AndroidDriver<WebElement>) appiumDriver)
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + text + "\")");
TouchAction touchAction = new TouchAction(appiumDriver);
touchAction.longPress(10, 10).moveTo(element.getLocation().getX(), element.getLocation().getY()).release()
.perform();
} catch (Exception e) {
clickOnPhone(DeviceActions.BACK);
scrollDownToHiddenElementByName(text);
e.printStackTrace();
}
}
public void scroll(int y_coordinate) {
appiumDriver = new Driver().getAppiumDriver();
Dimension dimens = appiumDriver.manage().window().getSize();
int x = (int) (dimens.getWidth() * 0.5);
int startY = (int) (dimens.getHeight() * 0.5);
new TouchAction(appiumDriver).press(x, startY).waitAction(Duration.ofMillis(2000)).moveTo(x, y_coordinate)
.release().perform();
}
public void scrollToExactElement(String str) {
appiumDriver = new Driver().getAppiumDriver();
((AndroidDriver<WebElement>) appiumDriver).findElementByAndroidUIAutomator(
"new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text(\""
+ str + "\").instance(0))")
.click();
}
public void scrollToElement(String str) {
appiumDriver = new Driver().getAppiumDriver();
((AndroidDriver<WebElement>) appiumDriver).findElementByAndroidUIAutomator(
"new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""
+ str + "\").instance(0))");
}
/**
* scrollDownToHiddenElementByName
*
* @param elementName
*/
public void scrollDownToHiddenElementByName(String elementName,AppiumDriver<WebElement> appiumDriver) {
Dimension dimens = appiumDriver.manage().window().getSize();
int x = (int) (dimens.getWidth() * 0.5);
int startY = (int) (dimens.getHeight() * 0.5);
int endY = (int) (dimens.getHeight() * 0.2);
try {
if (appiumDriver.findElement(By.xpath("//*[contains(@text, '" + elementName + "')]")).isDisplayed()) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
try {
new TouchAction(appiumDriver).press(0, startY).waitAction(Duration.ofMillis(2000)).moveTo(x, endY)
.release().perform();
if (appiumDriver.findElement(By.xpath("//*[contains(@text, '" + elementName + "')]")).isDisplayed()) {
scrollTo(elementName);
break;
}
} catch (Exception e) {
}
}
}
/**
* takeScreenShot
*
* @param failureImageFileName
* @param appiumDriver
* @return
*/
public File takeScreenShot(String failureImageFileName, AppiumDriver<WebElement> appiumDriver) {
File scrFile = ((TakesScreenshot) appiumDriver).getScreenshotAs(OutputType.FILE);
File destFile = null;
try {
destFile = new File(OUTPUT_PATH + "//" + commonUtils.getCurrentTimeAndDate("yyyy-MM-dd-HH-mm-ss") + ".png");
FileUtils.copyFile(scrFile, destFile);
} catch (IOException e) {
e.printStackTrace();
}
return destFile;
}
/**
* takeScreenShot
*
* @param failureImageFileName
* @param appiumDriver
* @return
*/
public File takeScreenShot(AppiumDriver<WebElement> appiumDriver) {
File scrFile = ((TakesScreenshot) appiumDriver).getScreenshotAs(OutputType.FILE);
File destFile = null;
try {
destFile = new File(OUTPUT_PATH + "//" + commonUtils.getCurrentTimeAndDate("yyyy-MM-dd-HH-mm-ss") + ".png");
FileUtils.copyFile(scrFile, destFile);
} catch (IOException e) {
e.printStackTrace();
}
return destFile;
}
/**
* isElementDisplayedByName
*
* @param elementName
* @return
*/
public boolean isElementDisplayedByNameAfterScrolling(String elementName, AppiumDriver<WebElement> appiumDriver) {
try {
if (((AndroidDriver<WebElement>) appiumDriver)
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + elementName + "\")")
.isDisplayed())
return true;
scrollDownToHiddenElementByName(elementName);
return ((AndroidDriver<WebElement>) appiumDriver)
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + elementName + "\")")
.isDisplayed();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* isElementDisplayedByName
*
* @param elementName
* @return
*/
public boolean isElementDisplayedByName(String elementName, AppiumDriver<WebElement> appiumDriver) {
try {
return appiumDriver.findElement(By.xpath("//*[contains(@text, '" + elementName + "')]")).isDisplayed();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public int getNumberOfElementDisplayedByName(String elementName, AppiumDriver<WebElement> appiumDriver) {
try {
return appiumDriver.findElements(By.xpath("//*[contains(@text, '" + elementName + "')]")).size();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* clickElementByName
*
* @param element
*/
public boolean clickElementByName(String element, AppiumDriver<WebElement> appiumDriver) {
try {
WebElement tempElement = new FluentWait<AppiumDriver<WebElement>>(appiumDriver)
.withTimeout(Duration.ofMillis(5000)).ignoring(StaleElementReferenceException.class)
.pollingEvery(Duration.ofMillis(3000))
.until(ExpectedConditions.visibilityOf(((AndroidDriver<WebElement>) appiumDriver)
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + element + "\")")));
tempElement.click();
return true;
} catch (Exception e) {
e.printStackTrace();
try {
((AndroidDriver<WebElement>) appiumDriver).findElementByXPath("//*[@text='" + element + "']");
} catch (Exception e1) {
e1.printStackTrace();
return false;
}
return false;
}
}
/**
* clickElementByName
*
* @param element
*/
public void clickElementByName(String element, AppiumDriver<WebElement> appiumDriver) {
try {
((AndroidDriver<WebElement>) appiumDriver)
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + element + "\")");
} catch (Exception e) {
((AndroidDriver<WebElement>) appiumDriver).findElementByXPath("//*[@text='" + element + "']");
e.printStackTrace();
}
}
/**
* clickElementByLocator
* @param locator
* @param index
* @return
*/
public boolean clickElementByLocator(By locator, int index, AppiumDriver<WebElement> appiumDriver) {
try {
appiumDriver.findElements(locator).get(index).click();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* isSomeTextFieldDisplayed
*
* @return
*/
public boolean isSomeTextFieldDisplayed(AppiumDriver<WebElement> appiumDriver) {
try {
return appiumDriver.findElement(By.className("android.widget.EditText")).isDisplayed();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* tapOnScreen
*
* @param element
* @param extentX
* @param extentY
* @return
*/
public String tapOnScreen(WebElement element, int extentX, int extentY) {
Point point = element.getLocation();
Dimension size = element.getSize();
int elementCenterX = 0, elementCenterY = 0;
try {
elementCenterX = point.getX() + Math.round(size.getWidth() / 2);
elementCenterY = point.getY() + Math.round(size.getHeight() / 2);
tapOnScreen(elementCenterX + extentX, elementCenterY + extentY);
return String.valueOf(elementCenterX + extentX) + "," + String.valueOf(elementCenterY + extentY);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* tapOnScreen
*
* @param X
* @param Y
* @return
*/
public boolean tapOnScreen(int X, int Y, AppiumDriver<WebElement> appiumDriver) {
try {
TouchAction touchAction = new TouchAction((AndroidDriver<?>) appiumDriver);
touchAction.tap(X, Y).perform().release();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* getDimensionOfElement
*
* @param element
* @return
*/
public Dimension getDimensionOfElement(WebElement element) {
Dimension dimension = element.getSize();
return dimension;
}
/**
* turnWiFiOnOrOff
*
* @param connection
*/
@SuppressWarnings("rawtypes")
public boolean turnWiFiOnOrOff(Connection connection, AppiumDriver<WebElement> appiumDriver) {
try {
((AndroidDriver) appiumDriver).setConnection(connection);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* getElementTextBy
*
* @param locator
* @return
*/
public String getElementTextBy(By locator, AppiumDriver<WebElement> appiumDriver) {
return appiumDriver.findElement(locator).getText();
}
/**
* IsElementTextDisplayed
*
* @param locator
* @return
*/
public boolean isElementTextDisplayed(By locator, String expectedText, AppiumDriver<WebElement> appiumDriver) {
List<WebElement> elements = appiumDriver.findElements(locator);
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getText().equalsIgnoreCase(expectedText))
return true;
}
return false;
}
/**
* getElementTextBy
*
* @param locator
* @return
*/
public String getElementTextBy(WebElement element) {
return element.getText();
}
/**
* getElementTextByIndex
*
* @param locator
* @return
*/
public String getElementsTextBy(By locator, int index, AppiumDriver<WebElement> appiumDriver) {
return appiumDriver.findElements(locator).get(index).getText();
}
/**
* executeADBCommand
*
* @param command
* @return
*/
public String executeADBCommand(String command, AppiumDriver<WebElement> appiumDriver) {
CommandPrompt commandPrompt = new CommandPrompt();
String output = commandPrompt
.runCommand(System.getProperty("user.dir") + "\\resources\\adb\\adb.exe " + command);
return output;
}
/**
* setTextForDecisionTreeTextFields
*
* @param text
* @return
*/
public boolean setTextForDecisionTreeTextFields(String text, AppiumDriver<WebElement> appiumDriver) {
try {
appiumDriver.findElement(By.className("android.widget.EditText")).sendKeys(text);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* getImageWidth
*
* @param file
* @return
*/
public int getImageWidth(File file) {
try {
BufferedImage image = ImageIO.read(file);
return image.getWidth();
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
public void waitforElementByName(int timeout, String element, AppiumDriver<WebElement> appiumDriver) {
try {
new FluentWait<AppiumDriver<WebElement>>(appiumDriver).withTimeout(Duration.ofMillis(timeout))
.ignoring(NoSuchElementException.class).pollingEvery(Duration.ofMillis(2000))
.until(ExpectedConditions
.visibilityOfElementLocated(By.xpath("//*[contains(@text, '" + element + "')]")));
} catch (Exception e) {
e.printStackTrace();
}
}
public void hideKeyboard(AppiumDriver<WebElement> appiumDriver) {
try {
((AndroidDriver<WebElement>) appiumDriver).hideKeyboard();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getDeviceID() {
return executeADBCommand("shell settings get secure android_id");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment