Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement.castDriver
Source:IAndroidUtils.java
...77 static final String SHELL_ENABLE_GPS_CMD = "settings put secure location_providers_allowed +gps";78 static final String SHELL_PRESS_HOME_CMD = "input keyevent 3";79 static final String SHELL_RECENT_APPS_CMD = "input keyevent KEYCODE_APP_SWITCH";80 default public void pressKeyboardKey(AndroidKey key) {81 ((AndroidDriver<?>) castDriver()).pressKey(new KeyEvent(key).withFlag(KeyEventFlag.SOFT_KEYBOARD)82 .withFlag(KeyEventFlag.KEEP_TOUCH_MODE).withFlag(KeyEventFlag.EDITOR_ACTION));83 }84 default public void pressBack() {85 ((AndroidDriver<?>) castDriver()).pressKey(new KeyEvent(AndroidKey.BACK));86 }87 /**88 * Pressing "search" key of Android keyboard by coordinates.89 * <p>90 * Tested at Nexus 6P Android 8.0.0 standard keyboard. Coefficients of91 * coordinates for other devices and custom keyboards could be different.92 * <p>93 * Following options are not working: 1.94 * AndroidDriver.pressKeyCode(AndroidKeyCode.KEYCODE_SEARCH); 2.95 * searchEditText.sendKeys("textToSearch" + "\n")96 */97 default public void pressSearchKey() {98 pressBottomRightKey();99 }100 default public void pressNextKey() {101 pressBottomRightKey();102 }103 // Change Device Language section104 /**105 * change Android Device Language106 * <p>107 * Url: <a href=108 * "http://play.google.com/store/apps/details?id=net.sanapeli.adbchangelanguage">109 * ADBChangeLanguage apk </a> Change locale (language) of your device via ADB110 * (on Android OS version 6.0, 5.0, 4.4, 4.3, 4.2 and older). No need to root111 * your device! With ADB (Android Debug Bridge) on your computer, you can fast112 * switch the device locale to see how your application UI looks on different113 * languages. Usage: - install this app - setup adb connection to your device114 * (http://developer.android.com/tools/help/adb.html) - Android OS 4.2 onwards115 * (tip: you can copy the command here and paste it to your command console):116 * adb shell pm grant net.sanapeli.adbchangelanguage117 * android.permission.CHANGE_CONFIGURATION118 * <p>119 * English: adb shell am start -n120 * net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language en Russian: adb121 * shell am start -n net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e122 * language ru Spanish: adb shell am start -n123 * net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language es124 *125 * @param language126 * to set. Can be es, en, etc.127 * @return boolean128 */129 default public boolean setDeviceLanguage(String language) {130 boolean status = setDeviceLanguage(language, 20);131 return status;132 }133 /**134 * change Android Device Language135 * <p>136 * Url: <a href=137 * "http://play.google.com/store/apps/details?id=net.sanapeli.adbchangelanguage">138 * ADBChangeLanguage apk </a> Change locale (language) of your device via ADB139 * (on Android OS version 6.0, 5.0, 4.4, 4.3, 4.2 and older). No need to root140 * your device! With ADB (Android Debug Bridge) on your computer, you can fast141 * switch the device locale to see how your application UI looks on different142 * languages. Usage: - install this app - setup adb connection to your device143 * (http://developer.android.com/tools/help/adb.html) - Android OS 4.2 onwards144 * (tip: you can copy the command here and paste it to your command console):145 * adb shell pm grant net.sanapeli.adbchangelanguage146 * android.permission.CHANGE_CONFIGURATION147 * <p>148 * English: adb shell am start -n149 * net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language en Russian: adb150 * shell am start -n net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e151 * language ru Spanish: adb shell am start -n152 * net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language es153 *154 * @param language155 * to set. Can be es, en, etc.156 * @param waitTime157 * int wait in seconds before device refresh.158 * @return boolean159 */160 default public boolean setDeviceLanguage(String language, int waitTime) {161 boolean status = false;162 UTILS_LOGGER.info("Do not concat language for Android. Keep: " + language);163 language = language.replace("_", "-");164 UTILS_LOGGER.info("Refactor language to : " + language);165 String actualDeviceLanguage = getDeviceLanguage();166 if (language.contains(actualDeviceLanguage.toLowerCase())167 || actualDeviceLanguage.toLowerCase().contains(language)) {168 UTILS_LOGGER.info("Device already have expected language: " + actualDeviceLanguage);169 return true;170 }171 String setLocalizationChangePermissionCmd = "shell pm grant net.sanapeli.adbchangelanguage android.permission.CHANGE_CONFIGURATION";172 String setLocalizationCmd = "shell am start -n net.sanapeli.adbchangelanguage/.AdbChangeLanguage -e language "173 + language;174 UTILS_LOGGER.info("Try set localization change permission with following cmd:" + setLocalizationChangePermissionCmd);175 String expandOutput = executeAdbCommand(setLocalizationChangePermissionCmd);176 String pathToInstalledAppCmd = "shell pm path net.sanapeli.adbchangelanguage";177 String pathToInstalledApp = executeAdbCommand(pathToInstalledAppCmd);178 if (expandOutput.contains("Unknown package: net.sanapeli.adbchangelanguage") || pathToInstalledApp.isEmpty()) {179 UTILS_LOGGER.info("Looks like 'ADB Change Language apk' is not installed. Install it and try again.");180 installApk(LANGUAGE_CHANGE_APP_PATH, true);181 expandOutput = executeAdbCommand(setLocalizationChangePermissionCmd);182 }183 UTILS_LOGGER.info("Output after set localization change permission using 'ADB Change Language apk': " + expandOutput);184 UTILS_LOGGER.info("Try set localization to '" + language + "' with following cmd: " + setLocalizationCmd);185 String changeLocaleOutput = executeAdbCommand(setLocalizationCmd);186 UTILS_LOGGER.info("Output after set localization to '" + language + "' using 'ADB Change Language apk' : "187 + changeLocaleOutput);188 if (waitTime > 0) {189 UTILS_LOGGER.info("Wait for at least '" + waitTime + "' seconds before device refresh.");190 CommonUtils.pause(waitTime);191 }192 actualDeviceLanguage = getDeviceLanguage();193 UTILS_LOGGER.info("Actual Device Language: " + actualDeviceLanguage);194 if (language.contains(actualDeviceLanguage.toLowerCase())195 || actualDeviceLanguage.toLowerCase().contains(language)) {196 status = true;197 } else {198 if (getDeviceLanguage().isEmpty()) {199 UTILS_LOGGER.info("Adb return empty response without errors.");200 status = true;201 } else {202 String currentAndroidVersion = IDriverPool.getDefaultDevice().getOsVersion();203 UTILS_LOGGER.info("currentAndroidVersion=" + currentAndroidVersion);204 if (currentAndroidVersion.contains("7.")) {205 UTILS_LOGGER.info("Adb return language command do not work on some Android 7+ devices."206 + " Check that there are no error.");207 status = !getDeviceLanguage().toLowerCase().contains("error");208 }209 }210 }211 return status;212 }213 /**214 * getDeviceLanguage215 *216 * @return String217 */218 default public String getDeviceLanguage() {219 String locale = executeAdbCommand("shell getprop persist.sys.language");220 if (locale.isEmpty()) {221 locale = executeAdbCommand("shell getprop persist.sys.locale");222 }223 return locale;224 }225 // End Language Change section226 /**227 * install android Apk by path to apk file.228 *229 * @param apkPath230 * String231 */232 default public void installApk(final String apkPath) {233 installApk(apkPath, false);234 }235 /**236 * install android Apk by path to apk or by name in classpath.237 *238 * @param apkPath239 * String240 * @param inClasspath241 * boolean242 */243 default public void installApk(final String apkPath, boolean inClasspath) {244 String filePath = apkPath;245 if (inClasspath) {246 URL baseResource = ClassLoader.getSystemResource(apkPath);247 if (baseResource == null) {248 throw new RuntimeException("Unable to get resource from classpath: " + apkPath);249 } else {250 UTILS_LOGGER.debug("Resource was found: " + baseResource.getPath());251 }252 String fileName = FilenameUtils.getBaseName(baseResource.getPath()) + "."253 + FilenameUtils.getExtension(baseResource.getPath());254 // make temporary copy of resource in artifacts folder255 filePath = ReportContext.getArtifactsFolder().getAbsolutePath() + File.separator + fileName;256 File file = new File(filePath);257 if (!file.exists()) {258 InputStream link = (ClassLoader.getSystemResourceAsStream(apkPath));259 try {260 Files.copy(link, file.getAbsoluteFile().toPath());261 } catch (IOException e) {262 UTILS_LOGGER.error("Unable to extract resource from ClassLoader!", e);263 }264 }265 }266 executeAdbCommand("install " + filePath);267 }268 public enum SelectorType {269 TEXT,270 TEXT_CONTAINS,271 TEXT_STARTS_WITH,272 ID,273 DESCRIPTION,274 DESCRIPTION_CONTAINS,275 CLASS_NAME276 }277 /**278 * Scrolls into view in specified container by text only and return boolean279 *280 * @param container281 * ExtendedWebElement - defaults to id Selector Type282 * @param scrollToElement283 * String defaults to text Selector Type284 * @return ExtendedWebElement285 * <p>286 * example of usage: ExtendedWebElement res =287 * AndroidUtils.scroll("News", newsListContainer);288 **/289 default public ExtendedWebElement scroll(String scrollToElement, ExtendedWebElement container) {290 return scroll(scrollToElement, container, SelectorType.ID, SelectorType.TEXT);291 }292 /**293 * Scrolls into view in a container specified by it's instance (index)294 * 295 * @param scrollToEle296 * - has to be id, text, contentDesc or className297 * @param scrollableContainer298 * - ExtendedWebElement type299 * @param containerSelectorType300 * - has to be id, text, textContains, textStartsWith, Description,301 * DescriptionContains or className302 * @param containerInstance303 * - has to an instance number of desired container304 * @param eleSelectorType305 * - has to be id, text, textContains, textStartsWith, Description,306 * DescriptionContains or className307 * @return ExtendedWebElement308 * <p>309 * example of usage: ExtendedWebElement res =310 * AndroidUtils.scroll("News", newsListContainer,311 * AndroidUtils.SelectorType.CLASS_NAME, 1,312 * AndroidUtils.SelectorType.TEXT);313 **/314 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,315 SelectorType containerSelectorType, int containerInstance, SelectorType eleSelectorType) {316 ExtendedWebElement extendedWebElement = null;317 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());318 // TODO: support multi threaded WebDriver's removing DriverPool usage319 WebDriver drv = castDriver();320 // workaorund for appium issue: https://github.com/appium/appium/issues/10159321 if (scrollToEle.contains(",")) {322 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);323 if (eleSelectorType.equals(SelectorType.TEXT)) {324 eleSelectorType = SelectorType.TEXT_CONTAINS;325 }326 }327 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {328 try {329 By scrollBy = MobileBy.AndroidUIAutomator("new UiScrollable("330 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ".instance("331 + containerInstance + "))" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")"332 + ".scrollIntoView(" + getScrollToElementSelector(scrollToEle, eleSelectorType) + ")");333 WebElement ele = drv.findElement(scrollBy);334 if (ele.isDisplayed()) {335 UTILS_LOGGER.info("Element found!!!");336 // initializing with driver context because scrollBy consists from container and element selectors337 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);338 break;339 }340 } catch (NoSuchElementException noSuchElement) {341 UTILS_LOGGER.error(String.format("%s %s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),342 noSuchElement);343 }344 for (int j = 0; j < i; j++) {345 checkTimeout(startTime);346 MobileBy.AndroidUIAutomator(347 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)348 + ".instance(" + containerInstance + ")).scrollForward()");349 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");350 }351 }352 return extendedWebElement;353 }354 /**355 * Scrolls into view in specified container356 * 357 * @param scrollToEle358 * - has to be id, text, contentDesc or className359 * @param scrollableContainer360 * - ExtendedWebElement type361 * @param containerSelectorType362 * - has to be id, text, textContains, textStartsWith, Description,363 * DescriptionContains or className364 * @param containerInstance365 * - has to an instance number of desired container366 * @param eleSelectorType367 * - has to be id, text, textContains, textStartsWith, Description,368 * DescriptionContains or className369 * @param eleSelectorInstance370 * - has to an instance number of desired container371 * @return ExtendedWebElement372 * <p>373 * example of usage: ExtendedWebElement res =374 * AndroidUtils.scroll("News", newsListContainer,375 * AndroidUtils.SelectorType.CLASS_NAME, 1,376 * AndroidUtils.SelectorType.TEXT, 2);377 **/378 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,379 SelectorType containerSelectorType, int containerInstance, SelectorType eleSelectorType,380 int eleSelectorInstance) {381 ExtendedWebElement extendedWebElement = null;382 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());383 // TODO: support multi threaded WebDriver's removing DriverPool usage384 WebDriver drv = castDriver();385 // workaorund for appium issue: https://github.com/appium/appium/issues/10159386 if (scrollToEle.contains(",")) {387 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);388 if (eleSelectorType.equals(SelectorType.TEXT)) {389 eleSelectorType = SelectorType.TEXT_CONTAINS;390 }391 }392 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {393 try {394 By scrollBy = MobileBy.AndroidUIAutomator("new UiScrollable("395 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ".instance("396 + containerInstance + "))" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")"397 + ".scrollIntoView(" + getScrollToElementSelector(scrollToEle, eleSelectorType) + ".instance("398 + eleSelectorInstance + "))");399 WebElement ele = drv.findElement(scrollBy);400 if (ele.isDisplayed()) {401 UTILS_LOGGER.info("Element found!!!");402 // initializing with driver context because scrollBy consists from container and element selectors403 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);404 break;405 }406 } catch (NoSuchElementException noSuchElement) {407 UTILS_LOGGER.error(String.format("%s%s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),408 noSuchElement);409 }410 for (int j = 0; j < i; j++) {411 checkTimeout(startTime);412 MobileBy.AndroidUIAutomator(413 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)414 + ".instance(" + containerInstance + ")).scrollForward()");415 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");416 }417 }418 return extendedWebElement;419 }420 /**421 * Scrolls into view in specified container422 * 423 * @param scrollToEle424 * - has to be id, text, contentDesc or className425 * @param scrollableContainer426 * - ExtendedWebElement type427 * @param containerSelectorType428 * - container Selector type: has to be id, text, textContains,429 * textStartsWith, Description, DescriptionContains or className430 * @param eleSelectorType431 * - scrollToEle Selector type: has to be id, text, textContains,432 * textStartsWith, Description, DescriptionContains or className433 * @return ExtendedWebElement434 * <p>435 * example of usage: ExtendedWebElement res =436 * AndroidUtils.scroll("News", newsListContainer,437 * AndroidUtils.SelectorType.CLASS_NAME,438 * AndroidUtils.SelectorType.TEXT);439 **/440 default public ExtendedWebElement scroll(String scrollToEle, ExtendedWebElement scrollableContainer,441 SelectorType containerSelectorType, SelectorType eleSelectorType) {442 ExtendedWebElement extendedWebElement = null;443 long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());444 // TODO: support multi threaded WebDriver's removing DriverPool usage445 WebDriver drv = castDriver();446 // workaorund for appium issue: https://github.com/appium/appium/issues/10159447 if (scrollToEle.contains(",")) {448 scrollToEle = StringUtils.join(StringUtils.split(scrollToEle, ","), ",", 0, 2);449 if (eleSelectorType.equals(SelectorType.TEXT)) {450 eleSelectorType = SelectorType.TEXT_CONTAINS;451 }452 }453 for (int i = 0; i < SCROLL_MAX_SEARCH_SWIPES; i++) {454 try {455 By scrollBy = MobileBy.AndroidUIAutomator(456 "new UiScrollable(" + getScrollContainerSelector(scrollableContainer, containerSelectorType)457 + ")" + ".setMaxSearchSwipes(" + SCROLL_MAX_SEARCH_SWIPES + ")" + ".scrollIntoView("458 + getScrollToElementSelector(scrollToEle, eleSelectorType) + ")");459 WebElement ele = drv.findElement(scrollBy);460 if (ele.isDisplayed()) {461 UTILS_LOGGER.info("Element found!!!");462 // initializing with driver context because scrollBy consists from container and element selectors463 extendedWebElement = new ExtendedWebElement(scrollBy, scrollToEle, drv, drv);464 break;465 }466 } catch (NoSuchElementException noSuchElement) {467 UTILS_LOGGER.error(String.format("%s%s:%s", SpecialKeywords.NO_SUCH_ELEMENT_ERROR, eleSelectorType, scrollToEle),468 noSuchElement);469 }470 for (int j = 0; j < i; j++) {471 checkTimeout(startTime);472 MobileBy.AndroidUIAutomator("new UiScrollable("473 + getScrollContainerSelector(scrollableContainer, containerSelectorType) + ").scrollForward()");474 UTILS_LOGGER.info("Scroller got stuck on a page, scrolling forward to next page of elements..");475 }476 }477 return extendedWebElement;478 }479 /**480 * Scrolls into view in specified container481 * 482 * @param scrollableContainer483 * - ExtendedWebElement type484 * @param containerSelectorType485 * - Selector type: has to be id, text, contentDesc or className486 * @return scrollViewContainerFinder String487 *488 **/489 default String getScrollContainerSelector(ExtendedWebElement scrollableContainer,490 SelectorType containerSelectorType) {491 UTILS_LOGGER.debug(scrollableContainer.getBy().toString());492 String scrollableContainerBy;493 String scrollViewContainerFinder = "";494 switch (containerSelectorType) {495 case TEXT:496 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.text:", "").trim();497 scrollViewContainerFinder = "new UiSelector().text(\"" + scrollableContainerBy + "\")";498 break;499 case TEXT_CONTAINS:500 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.textContains:", "").trim();501 scrollViewContainerFinder = "new UiSelector().textContains(\"" + scrollableContainerBy + "\")";502 break;503 case TEXT_STARTS_WITH:504 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.textStartsWith:", "").trim();505 scrollViewContainerFinder = "new UiSelector().textStartsWith(\"" + scrollableContainerBy + "\")";506 break;507 case ID:508 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.id:", "").trim();509 scrollViewContainerFinder = "new UiSelector().resourceId(\"" + scrollableContainerBy + "\")";510 break;511 case DESCRIPTION:512 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.description:", "").trim();513 scrollViewContainerFinder = "new UiSelector().description(\"" + scrollableContainerBy + "\")";514 break;515 case DESCRIPTION_CONTAINS:516 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.descriptionContains:", "")517 .trim();518 scrollViewContainerFinder = "new UiSelector().descriptionContains(\"" + scrollableContainerBy + "\")";519 break;520 case CLASS_NAME:521 scrollableContainerBy = scrollableContainer.getBy().toString().replace("By.className:", "").trim();522 scrollViewContainerFinder = "new UiSelector().className(\"" + scrollableContainerBy + "\")";523 break;524 default:525 UTILS_LOGGER.info("Please provide valid selectorType for element to be found...");526 break;527 }528 return scrollViewContainerFinder;529 }530 /**531 * Scrolls into view in specified container532 * 533 * @param scrollToEle534 * - String type535 * @param eleSelectorType536 * - Selector type: has to be id, text, contentDesc or className537 * @return String538 **/539 default String getScrollToElementSelector(String scrollToEle, SelectorType eleSelectorType) {540 String neededElementFinder = "";541 String scrollToEleTrimmed;542 switch (eleSelectorType) {543 case TEXT:544 neededElementFinder = "new UiSelector().text(\"" + scrollToEle + "\")";545 break;546 case TEXT_CONTAINS:547 neededElementFinder = "new UiSelector().textContains(\"" + scrollToEle + "\")";548 break;549 case TEXT_STARTS_WITH:550 neededElementFinder = "new UiSelector().textStartsWith(\"" + scrollToEle + "\")";551 break;552 case ID:553 scrollToEleTrimmed = scrollToEle.replace("By.id:", "").trim();554 neededElementFinder = "new UiSelector().resourceId(\"" + scrollToEleTrimmed + "\")";555 break;556 case DESCRIPTION:557 neededElementFinder = "new UiSelector().description(\"" + scrollToEle + "\")";558 break;559 case DESCRIPTION_CONTAINS:560 neededElementFinder = "new UiSelector().descriptionContains(\"" + scrollToEle + "\")";561 break;562 case CLASS_NAME:563 scrollToEleTrimmed = scrollToEle.replace("By.className:", "").trim();564 neededElementFinder = "new UiSelector().className(\"" + scrollToEleTrimmed + "\")";565 break;566 default:567 UTILS_LOGGER.info("Please provide valid selectorType for element to be found...");568 break;569 }570 return neededElementFinder;571 }572 /**573 * Scroll Timeout check574 * 575 * @param startTime576 * - Long initial time for timeout count down577 **/578 default public void checkTimeout(long startTime) {579 long elapsed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) - startTime;580 if (elapsed > SCROLL_TIMEOUT) {581 throw new NoSuchElementException("Scroll timeout has been reached..");582 }583 }584 /**585 * getCurrentDeviceFocus - get actual device apk in focus.586 *587 * @return String588 */589 default public String getCurrentDeviceFocus() {590 String result = executeAdbCommand("shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'");591 return result;592 }593 /**594 * executeAbdCommand595 *596 * @param command597 * String598 * @return String command output in one line599 */600 default public String executeAdbCommand(String command) {601 String deviceName = getDevice().getAdbName();602 if (!deviceName.isEmpty()) {603 // add remoteURL/udid reference604 command = "-s " + deviceName + " " + command;605 } else {606 UTILS_LOGGER.warn("nullDevice detected fot current thread!");607 }608 String result = "";609 UTILS_LOGGER.info("Command: " + command);610 String[] listOfCommands = command.split(" ");611 String[] execCmd = CmdLine.insertCommandsAfter(baseInitCmd, listOfCommands);612 try {613 UTILS_LOGGER.info("Try to execute following cmd: " + CmdLine.arrayToString(execCmd));614 List<String> execOutput = executor.execute(execCmd);615 UTILS_LOGGER.info("Output after execution ADB command: " + execOutput);616 result = execOutput.toString().replaceAll("\\[|\\]", "").replaceAll(", ", " ").trim();617 UTILS_LOGGER.info("Returning Output: " + result);618 } catch (Exception e) {619 UTILS_LOGGER.error("Error while executing adb command: " + command, e);620 }621 return result;622 }623 /**624 * 625 * @param command626 * 627 * - ADB shell command represented as single String where 1st literal628 * is a command itself. Everything that follow is treated as629 * arguments.630 *631 * NOTE: "adb -s {UDID} shell" - should be omitted.632 * Example: "adb -s {UDID} shell list packages" - list packages633 * 634 * NOTE: shell arguments with space symbols are unsupported!635 * 636 * @return String - response (might be empty)637 */638 default public String executeShell(String command) {639 UTILS_LOGGER.info("ADB command to be executed: adb shell ".concat(command.trim()));640 List<String> literals = Arrays.asList(command.split(" "));641 return executeShell(literals);642 }643 /**644 * 645 * @param commands list of string commands646 * 647 * - ADB shell command represented as single String where 1st literal648 * is a command itself. Everything that follow is treated as649 * arguments.650 *651 * NOTE: "adb -s {UDID} shell" - should be omitted.652 * Example: "adb -s {UDID} shell list packages" - list packages653 * 654 * @return String - response (might be empty)655 */656 default public String executeShell(List<String> commands) {657 String commadKeyWord = commands.get(0);658 List<String> args = commands.subList(1, commands.size());659 Map<String, Object> preparedCommand = ImmutableMap.of("command", commadKeyWord, "args", args);660 String output = (String) ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_CONSOLE, preparedCommand);661 if (!StringUtils.isEmpty(output)) {662 UTILS_LOGGER.debug("ADB command output: " + output);663 }664 return output;665 }666 /**667 * This method performs an action corresponding to press Android device's native668 * button to show all recent applications.669 * 670 * NOTE: method could be used to get a list of running in background671 * applications with respect to particular device.672 */673 default public void displayRecentApps() {674 executeShell(SHELL_RECENT_APPS_CMD);675 }676 /**677 * Tapping at native 'Home' button will be emulated. All applications will be678 * closed to background.679 */680 default public void pressHome() {681 executeShell(SHELL_PRESS_HOME_CMD);682 }683 /**684 * Is used to get GPS service status.685 * 686 * Response reflects which services are used for obtaining location:687 * 688 * - "gps" - GPS only (device only);689 * 690 * - "gps,network" - GPS + Wi-Fi + Bluetooth or cellular networks (High accuracy691 * mode);692 * 693 * - "network" - Using Wi-Fi, Bluetooth or cellular networks (Battery saving694 * mode);695 * 696 * @return boolean697 */698 default public boolean isGPSEnabled() {699 String response = executeShell(SHELL_GPS_STATUS_CMD);700 return response.contains("gps");701 }702 default public void enableGPS() {703 executeShell(SHELL_ENABLE_GPS_CMD);704 }705 /**706 * Works if ONLY DEVICE (GPS sensor) is user for obtaining location707 */708 default public void disableGPS() {709 executeShell(SHELL_DISABLE_GPS_CMD);710 }711 /**712 * This command will save screenshot to specified folder on device's OS using713 * provided path.714 * 715 * @param filepath716 * - path to save screenshot to device's OS (/storage/emulated/0/Download/scr.png).717 */718 default public void takeScreenShot(String filepath) {719 UTILS_LOGGER.info("Screenshot will be saved to: " + filepath);720 String command = String.format(SHELL_TAKE_SCREENSHOT_CMD.concat(" %s"), filepath);721 executeShell(command);722 }723 /**724 * This method provides app's version for the app that is already installed to725 * devices, based on its package name.726 * In order to do that we search for "versionCode" parameter in system dump.727 * 728 * @param packageName String729 * 730 * @return appVersion String731 */732 default public String getAppVersion(String packageName) {733 String command = "dumpsys package ".concat(packageName);734 String output = executeShell(command);735 String versionCode = StringUtils.substringBetween(output, "versionCode=", " ");736 UTILS_LOGGER.info(String.format("Version code for '%s' package name is %s", packageName, versionCode));737 return versionCode;738 }739 /**740 * This method provides app's version name for the app that is already installed to741 * devices, based on its package name.742 * In order to do that we search for "versionName" parameter in system dump.743 * Ex. "versionCode" returns 11200050, "versionName" returns 11.2.0744 * 745 * @param packageName String746 * @return appVersion String747 */748 default public String getAppVersionName(String packageName) {749 String command = "dumpsys package ".concat(packageName);750 String output = this.executeShell(command);751 String versionName = StringUtils.substringBetween(output, "versionName=", "\n");752 UTILS_LOGGER.info(String.format("Version name for '%s' package name is %s", packageName, versionName));753 return versionName;754 }755 /**756 * To open Android device native settings757 */758 default public void openDeviceSettings() {759 executeShell(SHELL_OPEN_DEVICE_SETTINGS_CMD);760 }761 /**762 * Method to reset test specific application by package name763 * 764 * App's settings will be reset. User will be logged out. Application will be765 * closed to background.766 * 767 * @param packageName String768 */769 default public void clearAppCache(String packageName) {770 UTILS_LOGGER.info("Will clear data for the following app: " + packageName);771 String command = String.format(SHELL_CLEAR_CACHE_CMD.concat(" %s"), packageName);772 String response = executeShell(command);773 UTILS_LOGGER.info(774 String.format("Output after resetting custom application by package (%s): ", packageName) + response);775 if (!response.contains("Success")) {776 UTILS_LOGGER.warn(String.format("App data was not cleared for %s app", packageName));777 }778 }779 /**780 * With this method user is able to trigger a deeplink (link to specific place781 * within the application) or event open URL in mobile browser.782 * 783 * NOTE, that to open URL in browser, URL should starts with "https://www.{place784 * your link here}".785 * 786 * NOTE that not all deeplinks require package name.787 * 788 * @param link789 * - URL to trigger790 */791 default public void openURL(String link) {792 // TODO: #1380 make openURL call from this mobile interface in DriverHelper793 UTILS_LOGGER.info("Following link will be triggered via ADB: " + link);794 String command = String.format(SHELL_OPEN_URL_CMD.concat(" %s"), link);795 executeShell(command);796 }797 /**798 * With this method user is able to trigger a deeplink (link to specific place799 * within the application)800 * 801 * @param link String802 * @param packageName String803 */804 default public void triggerDeeplink(String link, String packageName) {805 Map<String, Object> preparedCommand = ImmutableMap.of("url", link, "package", packageName);806 try {807 ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_DEEPLINK_CONSOLE, preparedCommand);808 } catch (WebDriverException wde) {809 // TODO: need to pay attention810 UTILS_LOGGER.warn("org.openqa.selenium.WebDriverException is caught and ignored.", wde);811 }812 }813 /**814 * To get list of granted/denied/requested permission for specified application815 * 816 * @param packageName String817 * @param type PermissionType818 * @return ArrayList String819 */820 @SuppressWarnings("unchecked")821 default public ArrayList<String> getAppPermissions(String packageName, PermissionType type) {822 Map<String, Object> preparedCommand = ImmutableMap.of("type", type.getType(), "package", packageName);823 return (ArrayList<String>) ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_GET_PERMISSION_CONSOLE,824 preparedCommand);825 }826 /**827 * To change (grant or revoke) application permissions.828 * 829 * @param packageName String830 * @param action PermissionAction831 * @param permissions Permission832 */833 default public void changePermissions(String packageName, PermissionAction action, Permission... permissions) {834 ArrayList<String> permissionsStr = new ArrayList<>();835 Arrays.asList(permissions).forEach(p -> permissionsStr.add(p.getPermission()));836 Map<String, Object> preparedCommand = ImmutableMap.of("action", action.getAction(), "appPackage", packageName,837 "permissions", permissionsStr);838 ((AppiumDriver<?>) castDriver()).executeScript(SHELL_INIT_CHANGE_PERMISSION_CONSOLE, preparedCommand);839 }840 /**841 * Method to enter text to ACTIVATED input field.842 * 843 * NOTE: that it might be necessary to escape some special characters.844 * Space-symbol is already escaped.845 * 846 * NOTE2: input field should be cleared previously.847 * 848 * @param text String849 */850 default public void typeWithADB(String text) {851 UTILS_LOGGER.info(String.format("Will enter '%s' to an active input field via ADB.", text));852 // In this method characters are entered one by one because sometimes some853 // characters might be omitted if to enter whole text at a time.854 char[] array = text.toCharArray();855 for (char sym : array) {856 String ch = (sym == ' ') ? "%s" : String.valueOf(sym);857 String command = SHELL_INPUT_TXT_CMD + ch;858 executeShell(command);859 }860 }861 default public boolean isWifiEnabled() {862 boolean enabled = ((AndroidDriver<?>) castDriver()).getConnection().isWiFiEnabled();863 UTILS_LOGGER.info("Wi-Fi enabled: " + enabled);864 return enabled;865 }866 default public void enableWifi() {867 boolean enabled = isWifiEnabled();868 if (!enabled) {869 ((AndroidDriver<?>) castDriver()).toggleWifi();870 return;871 }872 UTILS_LOGGER.info("Wifi is already anebled. No actions needed");873 }874 default public void disableWifi() {875 boolean enabled = isWifiEnabled();876 if (enabled) {877 ((AndroidDriver<?>) castDriver()).toggleWifi();878 return;879 }880 UTILS_LOGGER.info("Wifi is already disabled. No actions needed");881 }882 /**883 * Method enters an App's menu within device System Settings884 * 885 * @param appName - Name of the app as it appears in the device's Apps list (Language specific)886 */887 default void openAppMenuFromDeviceSettings(String appName) {888 AndroidService androidService = AndroidService.getInstance();889 androidService.executeAdbCommand("shell am start -a android.settings.APPLICATION_SETTINGS");890 // initializing appItem with ExtendedWebElement constructor that initialize search context891 ExtendedWebElement appItem = new ExtendedWebElement(By.xpath(String.format("//*[contains(@text, '%s')]", appName)), "notifications",892 getDriver(), getDriver());893 swipe(appItem);894 appItem.click();895 }896 /**897 * Toggles a specified app's ability to recieve Push Notifications on the system level898 * 899 * @param appName - The app name as it appears within device System Settings900 * @param setValue - The value you wish to set the toggle to901 */902 default void toggleAppNotificationsFromDeviceSettings(String appName, boolean setValue) {903 openAppMenuFromDeviceSettings(appName);904 WebDriver driver = getDriver();905 // initializing with driver context906 ExtendedWebElement element = new ExtendedWebElement(By.xpath("//*[contains(@text, 'Notifications') or contains(@text, 'notifications')]"),907 "notifications", driver, driver);908 element.click();909 // initializing with driver context910 element = new ExtendedWebElement(By.xpath("//*[@resource-id='com.android.settings:id/switch_text']/following-sibling::android.widget.Switch"),911 "toggle", driver, driver);912 if (Boolean.valueOf(element.getAttribute("checked")) != setValue) {913 element.click();914 }915 }916 /**917 * @return - Returns if the device in use has a running LTE connection918 */919 default boolean isCarrierConnectionAvailable() {920 AndroidService androidService = AndroidService.getInstance();921 boolean status = ((AndroidDriver) this.castDriver()).getConnection().isDataEnabled();922 boolean linkProperties = false;923 String linkProp = androidService.executeAdbCommand("shell dumpsys telephony.registry | grep mPreciseDataConnectionState");924 UTILS_LOGGER.info("PROP: " + linkProp);925 if (!linkProp.isEmpty()) {926 linkProperties = !StringUtils.substringBetween(linkProp, "APN: ", " ").equals("null");927 }928 UTILS_LOGGER.info("STATUS ENABLED: " + status);929 UTILS_LOGGER.info("CARRIER AVAILABLE: " + linkProperties);930 return ((AndroidDriver) this.castDriver()).getConnection().isDataEnabled() && linkProperties;931 }932 /**933 * @return - Returns the value of the device model in use as a String934 */935 default String getDeviceModel() {936 AndroidService androidService = AndroidService.getInstance();937 return StringUtils.substringAfter(androidService.executeAdbCommand("shell getprop | grep 'ro.product.model'"), "ro.product.model: ");938 }939 default public void openStatusBar() {940 executeShell(SHELL_OPEN_STATUS_BAR_CMD);941 }942 default public void closeStatusBar() {943 executeShell(SHELL_CLOSE_STATUS_BAR_CMD);944 }...
Source:IMobileUtils.java
...115 default public boolean longPress(ExtendedWebElement element) {116 UTILS_LOGGER.info("longPress on" + element.getName());117 // TODO: SZ migrate to FluentWaits118 try {119 WebDriver driver = castDriver();120 @SuppressWarnings("rawtypes")121 TouchAction<?> action = new TouchAction((MobileDriver<?>) driver);122 LongPressOptions options = LongPressOptions.longPressOptions().withElement(ElementOption.element(element.getElement()));123 action.longPress(options).release().perform();124 return true;125 } catch (Exception e) {126 UTILS_LOGGER.info("Error occurs during longPress: " + e, e);127 }128 return false;129 }130 /**131 * Tap with TouchAction by coordinates with custom duration132 *133 * @param startx int134 * @param starty int135 * @param duration int136 */137 default public void tap(int startx, int starty, int duration) {138 // TODO: add Screenshot.capture()139 try {140 @SuppressWarnings("rawtypes")141 TouchAction<?> touchAction = new TouchAction((MobileDriver<?>) castDriver());142 PointOption<?> startPoint = PointOption.point(startx, starty);143 WaitOptions waitOptions = WaitOptions.waitOptions(Duration.ofMillis(duration));144 if (duration == 0) {145 // do not perform waiter as using 6.0.0. appium java client we do longpress instead of simple tap even with 0 wait duration146 touchAction.press(startPoint).release().perform();147 } else {148 touchAction.press(startPoint).waitAction(waitOptions).release().perform();149 }150 Messager.TAP_EXECUTED.info(String.valueOf(startx), String.valueOf(starty));151 } catch (Exception e) {152 Messager.TAP_NOT_EXECUTED.error(String.valueOf(startx), String.valueOf(starty));153 throw e;154 }155 }156 /**157 * swipe till element using TouchActions158 *159 * @param element ExtendedWebElement160 * @return boolean161 */162 default public boolean swipe(final ExtendedWebElement element) {163 return swipe(element, null, Direction.UP, DEFAULT_MAX_SWIPE_COUNT, DEFAULT_TOUCH_ACTION_DURATION);164 }165 /**166 * swipe till element using TouchActions167 *168 * @param element ExtendedWebElement169 * @param count int170 * @return boolean171 */172 default public boolean swipe(final ExtendedWebElement element, int count) {173 return swipe(element, null, Direction.UP, count, DEFAULT_TOUCH_ACTION_DURATION);174 }175 /**176 * swipe till element using TouchActions177 *178 * @param element ExtendedWebElement179 * @param direction Direction180 * @return boolean181 */182 default public boolean swipe(final ExtendedWebElement element, Direction direction) {183 return swipe(element, null, direction, DEFAULT_MAX_SWIPE_COUNT, DEFAULT_TOUCH_ACTION_DURATION);184 }185 /**186 * swipe till element using TouchActions187 *188 * @param element ExtendedWebElement189 * @param count int190 * @param duration int191 * @return boolean192 */193 default public boolean swipe(final ExtendedWebElement element, int count, int duration) {194 return swipe(element, null, Direction.UP, count, duration);195 }196 /**197 * swipe till element using TouchActions198 *199 * @param element ExtendedWebElement200 * @param direction Direction201 * @param count int202 * @param duration int203 * @return boolean204 */205 default public boolean swipe(final ExtendedWebElement element, Direction direction, int count, int duration) {206 return swipe(element, null, direction, count, duration);207 }208 /**209 * Swipe inside container in default direction - Direction.UP210 * Number of attempts is limited by count argument211 * <p>212 *213 * @param element214 * ExtendedWebElement215 * @param container216 * ExtendedWebElement217 * @param count218 * int219 * @return boolean220 */221 default public boolean swipe(ExtendedWebElement element, ExtendedWebElement container, int count) {222 return swipe(element, container, Direction.UP, count, DEFAULT_TOUCH_ACTION_DURATION);223 }224 /**225 * Swipe inside container in default direction - Direction.UP226 * Number of attempts is limited by 5227 * <p>228 *229 * @param element230 * ExtendedWebElement231 * @param container232 * ExtendedWebElement233 * @return boolean234 */235 default public boolean swipe(ExtendedWebElement element, ExtendedWebElement container) {236 return swipe(element, container, Direction.UP, DEFAULT_MAX_SWIPE_COUNT, DEFAULT_TOUCH_ACTION_DURATION);237 }238 /**239 * Swipe inside container in specified direction240 * Number of attempts is limited by 5241 * <p>242 *243 * @param element244 * ExtendedWebElement245 * @param container246 * ExtendedWebElement247 * @param direction248 * Direction249 * @return boolean250 */251 default public boolean swipe(ExtendedWebElement element, ExtendedWebElement container, Direction direction) {252 return swipe(element, container, direction, DEFAULT_MAX_SWIPE_COUNT, DEFAULT_TOUCH_ACTION_DURATION);253 }254 /**255 * Swipe inside container in specified direction with default pulling timeout in 1000ms256 * Number of attempts is limited by count argument257 * <p>258 *259 * @param element260 * ExtendedWebElement261 * @param container262 * ExtendedWebElement263 * @param direction264 * Direction265 * @param count266 * int267 * @return boolean268 */269 default public boolean swipe(ExtendedWebElement element, ExtendedWebElement container, Direction direction,270 int count) {271 return swipe(element, container, direction, count, DEFAULT_TOUCH_ACTION_DURATION);272 }273 /**274 * Swipe to element inside container in specified direction while element275 * will not be present on the screen. If element is on the screen already,276 * scrolling will not be performed.277 * <p>278 *279 * @param element280 * element to which it will be scrolled281 * @param container282 * element, inside which scrolling is expected. null to scroll283 * @param direction284 * direction of scrolling. HORIZONTAL and VERTICAL support swiping in both directions automatically285 * @param count286 * for how long to scroll, ms287 * @param duration288 * pulling timeout, ms289 * @return boolean290 */291 default public boolean swipe(ExtendedWebElement element, ExtendedWebElement container, Direction direction,292 int count, int duration) {293 boolean isVisible = element.isVisible(1);294 if (isVisible) {295 // no sense to continue;296 UTILS_LOGGER.info("element already present before swipe: " + element.getNameWithLocator().toString());297 return true;298 } else {299 UTILS_LOGGER.info("swiping to element: " + element.getNameWithLocator().toString());300 }301 Direction oppositeDirection = Direction.DOWN;302 boolean bothDirections = false;303 switch (direction) {304 case UP:305 oppositeDirection = Direction.DOWN;306 break;307 case DOWN:308 oppositeDirection = Direction.UP;309 break;310 case LEFT:311 oppositeDirection = Direction.RIGHT;312 break;313 case RIGHT:314 oppositeDirection = Direction.LEFT;315 break;316 case HORIZONTAL:317 direction = Direction.LEFT;318 oppositeDirection = Direction.RIGHT;319 bothDirections = true;320 break;321 case HORIZONTAL_RIGHT_FIRST:322 direction = Direction.RIGHT;323 oppositeDirection = Direction.LEFT;324 bothDirections = true;325 break;326 case VERTICAL:327 direction = Direction.UP;328 oppositeDirection = Direction.DOWN;329 bothDirections = true;330 break;331 case VERTICAL_DOWN_FIRST:332 direction = Direction.DOWN;333 oppositeDirection = Direction.UP;334 bothDirections = true;335 break;336 default:337 throw new RuntimeException("Unsupported direction for swipeInContainerTillElement: " + direction);338 }339 int currentCount = count;340 while (!isVisible && currentCount-- > 0) {341 UTILS_LOGGER.debug("Element not present! Swipe " + direction + " will be executed to element: " + element.getNameWithLocator().toString());342 swipeInContainer(container, direction, duration);343 UTILS_LOGGER.info("Swipe was executed. Attempts remain: " + currentCount);344 isVisible = element.isVisible(1);345 }346 currentCount = count;347 while (bothDirections && !isVisible && currentCount-- > 0) {348 UTILS_LOGGER.debug(349 "Element not present! Swipe " + oppositeDirection + " will be executed to element: " + element.getNameWithLocator().toString());350 swipeInContainer(container, oppositeDirection, duration);351 UTILS_LOGGER.info("Swipe was executed. Attempts remain: " + currentCount);352 isVisible = element.isVisible(1);353 }354 UTILS_LOGGER.info("Result: " + isVisible);355 return isVisible;356 }357 /**358 * Swipe by coordinates using TouchAction (platform independent)359 *360 * @param startx int361 * @param starty int362 * @param endx int363 * @param endy int364 * @param duration int Millis365 */366 @SuppressWarnings("rawtypes")367 default public void swipe(int startx, int starty, int endx, int endy, int duration) {368 UTILS_LOGGER.debug("Starting swipe...");369 WebDriver drv = castDriver();370 UTILS_LOGGER.debug("Getting driver dimension size...");371 Dimension scrSize = drv.manage().window().getSize();372 UTILS_LOGGER.debug("Finished driver dimension size...");373 // explicitly limit range of coordinates374 if (endx >= scrSize.width) {375 UTILS_LOGGER.warn("endx coordinate is bigger then device width! It will be limited!");376 endx = scrSize.width - 1;377 } else {378 endx = Math.max(1, endx);379 }380 if (endy >= scrSize.height) {381 UTILS_LOGGER.warn("endy coordinate is bigger then device height! It will be limited!");382 endy = scrSize.height - 1;383 } else {384 endy = Math.max(1, endy);385 }386 UTILS_LOGGER.debug("startx: " + startx + "; starty: " + starty + "; endx: " + endx + "; endy: " + endy387 + "; duration: " + duration);388 PointOption<?> startPoint = PointOption.point(startx, starty);389 PointOption<?> endPoint = PointOption.point(endx, endy);390 WaitOptions waitOptions = WaitOptions.waitOptions(Duration.ofMillis(duration));391 new TouchAction((MobileDriver<?>) drv).press(startPoint).waitAction(waitOptions).moveTo(endPoint).release()392 .perform();393 UTILS_LOGGER.debug("Finished swipe...");394 }395 /**396 * swipeInContainer397 *398 * @param container ExtendedWebElement399 * @param direction Direction400 * @param duration int401 * @return boolean402 */403 default public boolean swipeInContainer(ExtendedWebElement container, Direction direction, int duration) {404 return swipeInContainer(container, direction, DEFAULT_MIN_SWIPE_COUNT, duration);405 }406 /**407 * swipeInContainer408 *409 * @param container ExtendedWebElement410 * @param direction Direction411 * @param count int412 * @param duration int413 * @return boolean414 */415 default public boolean swipeInContainer(ExtendedWebElement container, Direction direction, int count, int duration) {416 int startx = 0;417 int starty = 0;418 int endx = 0;419 int endy = 0;420 Point elementLocation = null;421 Dimension elementDimensions = null;422 if (container == null) {423 // whole screen/driver is a container!424 WebDriver driver = castDriver();425 elementLocation = new Point(0, 0); // initial left corner for that case426 elementDimensions = driver.manage().window().getSize();427 } else {428 if (container.isElementNotPresent(5)) {429 Assert.fail("Cannot swipe! Impossible to find element " + container.getName());430 }431 elementLocation = container.getLocation();432 elementDimensions = container.getSize();433 }434 double minCoefficient = 0.3;435 double maxCoefficient = 0.6;436 // calculate default coefficient based on OS type437 String os = IDriverPool.getDefaultDevice().getOs();438 if (os.equalsIgnoreCase(SpecialKeywords.ANDROID)) {439 minCoefficient = 0.25;440 maxCoefficient = 0.5;441 } else if (os.equalsIgnoreCase(SpecialKeywords.IOS) || os.equalsIgnoreCase(SpecialKeywords.MAC) || os.equalsIgnoreCase(SpecialKeywords.TVOS)) {442 minCoefficient = 0.25;443 maxCoefficient = 0.8;444 }445 switch (direction) {446 case LEFT:447 starty = endy = elementLocation.getY() + Math.round(elementDimensions.getHeight() / 2f);448 startx = (int) (elementLocation.getX() + Math.round(maxCoefficient * elementDimensions.getWidth()));449 endx = (int) (elementLocation.getX() + Math.round(minCoefficient * elementDimensions.getWidth()));450 break;451 case RIGHT:452 starty = endy = elementLocation.getY() + Math.round(elementDimensions.getHeight() / 2f);453 startx = (int) (elementLocation.getX() + Math.round(minCoefficient * elementDimensions.getWidth()));454 endx = (int) (elementLocation.getX() + Math.round(maxCoefficient * elementDimensions.getWidth()));455 break;456 case UP:457 startx = endx = elementLocation.getX() + Math.round(elementDimensions.getWidth() / 2f);458 starty = (int) (elementLocation.getY() + Math.round(maxCoefficient * elementDimensions.getHeight()));459 endy = (int) (elementLocation.getY() + Math.round(minCoefficient * elementDimensions.getHeight()));460 break;461 case DOWN:462 startx = endx = elementLocation.getX() + Math.round(elementDimensions.getWidth() / 2f);463 starty = (int) (elementLocation.getY() + Math.round(minCoefficient * elementDimensions.getHeight()));464 endy = (int) (elementLocation.getY() + Math.round(maxCoefficient * elementDimensions.getHeight()));465 break;466 default:467 throw new RuntimeException("Unsupported direction: " + direction);468 }469 UTILS_LOGGER.debug(String.format("Swipe from (X = %d; Y = %d) to (X = %d; Y = %d)", startx, starty, endx, endy));470 try {471 for (int i = 0; i < count; ++i) {472 swipe(startx, starty, endx, endy, duration);473 }474 return true;475 } catch (Exception e) {476 UTILS_LOGGER.error(String.format("Error during Swipe from (X = %d; Y = %d) to (X = %d; Y = %d): %s", startx, starty, endx, endy, e));477 }478 return false;479 }480 /**481 * Swipe up several times482 *483 * @param times int484 * @param duration int485 */486 default public void swipeUp(final int times, final int duration) {487 for (int i = 0; i < times; i++) {488 swipeUp(duration);489 }490 }491 /**492 * Swipe up493 *494 * @param duration int495 */496 default public void swipeUp(final int duration) {497 UTILS_LOGGER.info("Swipe up will be executed.");498 swipeInContainer(null, Direction.UP, duration);499 }500 /**501 * Swipe down several times502 *503 * @param times int504 * @param duration int505 */506 default public void swipeDown(final int times, final int duration) {507 for (int i = 0; i < times; i++) {508 swipeDown(duration);509 }510 }511 /**512 * Swipe down513 *514 * @param duration int515 */516 default public void swipeDown(final int duration) {517 UTILS_LOGGER.info("Swipe down will be executed.");518 swipeInContainer(null, Direction.DOWN, duration);519 }520 /**521 * Swipe left several times522 *523 * @param times int524 * @param duration int525 */526 default public void swipeLeft(final int times, final int duration) {527 for (int i = 0; i < times; i++) {528 swipeLeft(duration);529 }530 }531 /**532 * Swipe left533 *534 * @param duration int535 */536 default public void swipeLeft(final int duration) {537 UTILS_LOGGER.info("Swipe left will be executed.");538 swipeLeft(null, duration);539 }540 /**541 * Swipe left in container542 *543 * @param container544 * ExtendedWebElement545 * @param duration546 * int547 */548 default public void swipeLeft(ExtendedWebElement container, final int duration) {549 UTILS_LOGGER.info("Swipe left will be executed.");550 swipeInContainer(container, Direction.LEFT, duration);551 }552 /**553 * Swipe right several times554 *555 * @param times int556 * @param duration int557 */558 default public void swipeRight(final int times, final int duration) {559 for (int i = 0; i < times; i++) {560 swipeRight(duration);561 }562 }563 /**564 * Swipe right565 *566 * @param duration int567 */568 default public void swipeRight(final int duration) {569 UTILS_LOGGER.info("Swipe right will be executed.");570 swipeRight(null, duration);571 }572 /**573 * Swipe right in container574 *575 * @param container576 * ExtendedWebElement577 * @param duration578 * int579 */580 default public void swipeRight(ExtendedWebElement container, final int duration) {581 UTILS_LOGGER.info("Swipe right will be executed.");582 swipeInContainer(container, Direction.RIGHT, duration);583 }584 /**585 * Set Android Device Default TimeZone And Language based on config or to GMT and En586 * Without restoring actual focused apk.587 */588 default public void setDeviceDefaultTimeZoneAndLanguage() {589 setDeviceDefaultTimeZoneAndLanguage(false);590 }591 /**592 * set Android Device Default TimeZone And Language based on config or to GMT and En593 *594 * @param returnAppFocus - if true store actual Focused apk and activity, than restore after setting Timezone and Language.595 */596 default public void setDeviceDefaultTimeZoneAndLanguage(boolean returnAppFocus) {597 try {598 String baseApp = "";599 String os = IDriverPool.getDefaultDevice().getOs();600 if (os.equalsIgnoreCase(SpecialKeywords.ANDROID)) {601 AndroidService androidService = AndroidService.getInstance();602 if (returnAppFocus) {603 baseApp = androidService.getCurrentFocusedApkDetails();604 }605 String deviceTimezone = Configuration.get(Parameter.DEFAULT_DEVICE_TIMEZONE);606 String deviceTimeFormat = Configuration.get(Parameter.DEFAULT_DEVICE_TIME_FORMAT);607 String deviceLanguage = Configuration.get(Parameter.DEFAULT_DEVICE_LANGUAGE);608 DeviceTimeZone.TimeFormat timeFormat = DeviceTimeZone.TimeFormat.parse(deviceTimeFormat);609 DeviceTimeZone.TimeZoneFormat timeZone = DeviceTimeZone.TimeZoneFormat.parse(deviceTimezone);610 UTILS_LOGGER.info("Set device timezone to " + timeZone.toString());611 UTILS_LOGGER.info("Set device time format to " + timeFormat.toString());612 UTILS_LOGGER.info("Set device language to " + deviceLanguage);613 boolean timeZoneChanged = androidService.setDeviceTimeZone(timeZone.getTimeZone(), timeZone.getSettingsTZ(), timeFormat);614 boolean languageChanged = androidService.setDeviceLanguage(deviceLanguage);615 UTILS_LOGGER.info(String.format("Device TimeZone was changed to timeZone '%s' : %s. Device Language was changed to language '%s': %s",616 deviceTimezone,617 timeZoneChanged, deviceLanguage, languageChanged));618 if (returnAppFocus) {619 androidService.openApp(baseApp);620 }621 } else {622 UTILS_LOGGER.info(String.format("Current OS is %s. But we can set default TimeZone and Language only for Android.", os));623 }624 } catch (Exception e) {625 UTILS_LOGGER.error("Error while setting to device default timezone and language!", e);626 }627 }628 /**629 * Hide keyboard if needed630 */631 default public void hideKeyboard() {632 try {633 ((MobileDriver<?>) castDriver()).hideKeyboard();634 } catch (Exception e) {635 if (!e.getMessage().contains("Soft keyboard not present, cannot hide keyboard")) {636 UTILS_LOGGER.error("Exception appears during hideKeyboard: " + e);637 }638 }639 }640 /**641 * Check if keyboard is showing642 * return false if driver is not ios or android driver643 *644 * @return boolean645 */646 default public boolean isKeyboardShown() {647 MobileDriver<?> driver = (MobileDriver<?>) castDriver();648 if (driver instanceof IOSDriver) {649 return ((IOSDriver<?>) castDriver()).isKeyboardShown();650 }651 else if (driver instanceof AndroidDriver) {652 return ((AndroidDriver<?>) castDriver()).isKeyboardShown();653 }654 return false;655 }656 default public void zoom(Zoom type) {657 UTILS_LOGGER.info("Zoom will be performed :" + type);658 MobileDriver<?> driver = (MobileDriver<?>) castDriver();659 Dimension scrSize = driver.manage().window().getSize();660 int height = scrSize.getHeight();661 int width = scrSize.getWidth();662 UTILS_LOGGER.debug("Screen height : " + height);663 UTILS_LOGGER.debug("Screen width : " + width);664 Point point1 = new Point(width / 2, height / 2 - 30);665 Point point2 = new Point(width / 2, height / 10 * 3);666 Point point3 = new Point(width / 2, height / 2 + 30);667 Point point4 = new Point(width / 2, (7 * height) / 10);668 switch (type) {669 case OUT:670 zoom(point1.getX(), point1.getY(), point2.getX(), point2.getY(), point3.getX(), point3.getY(), point4.getX(), point4.getY(),671 DEFAULT_TOUCH_ACTION_DURATION);672 break;673 case IN:674 zoom(point2.getX(), point2.getY(), point1.getX(), point1.getY(), point4.getX(), point4.getY(), point3.getX(), point3.getY(),675 DEFAULT_TOUCH_ACTION_DURATION);676 break;677 }678 }679 default public void zoom(int startx1, int starty1, int endx1, int endy1, int startx2, int starty2, int endx2, int endy2, int duration) {680 UTILS_LOGGER.debug(String.format(681 "Zoom action will be performed with parameters : startX1 : %s ; startY1: %s ; endX1: %s ; endY1: %s; startX2 : %s ; startY2: %s ; endX2: %s ; endY2: %s",682 startx1, starty1, endx1, endy1, startx2, starty2, endx2, endy2));683 MobileDriver<?> driver = (MobileDriver<?>) castDriver();684 try {685 MultiTouchAction multiTouch = new MultiTouchAction(driver);686 @SuppressWarnings("rawtypes")687 TouchAction<?> tAction0 = new TouchAction(driver);688 @SuppressWarnings("rawtypes")689 TouchAction<?> tAction1 = new TouchAction(driver);690 PointOption<?> startPoint1 = PointOption.point(startx1, starty1);691 PointOption<?> endPoint1 = PointOption.point(endx1, endy1);692 PointOption<?> startPoint2 = PointOption.point(startx2, starty2);693 PointOption<?> endPoint2 = PointOption.point(endx2, endy2);694 WaitOptions waitOptions = WaitOptions.waitOptions(Duration.ofMillis(duration));695 tAction0.press(startPoint1).waitAction(waitOptions).moveTo(endPoint1).release();696 tAction1.press(startPoint2).waitAction(waitOptions).moveTo(endPoint2).release();697 multiTouch.add(tAction0).add(tAction1);698 multiTouch.perform();699 UTILS_LOGGER.info("Zoom has been performed");700 } catch (Exception e) {701 UTILS_LOGGER.error("Error during zooming", e);702 }703 }704 /**705 * Check if started driver/application is running in foreground706 *707 * @return boolean708 */709 default public boolean isAppRunning() {710 String bundleId = "";711 String os = getDevice().getOs();712 // get bundleId or appId of the application started by driver713 if (os.equalsIgnoreCase(SpecialKeywords.ANDROID)) {714 bundleId = ((AppiumDriver<?>) castDriver()).getSessionDetail(SpecialKeywords.APP_PACKAGE).toString();715 } else if (os.equalsIgnoreCase(SpecialKeywords.IOS) || os.equalsIgnoreCase(SpecialKeywords.MAC) || os.equalsIgnoreCase(SpecialKeywords.TVOS)) {716 bundleId = ((AppiumDriver<?>) castDriver()).getSessionDetail(SpecialKeywords.BUNDLE_ID).toString();717 }718 return isAppRunning(bundleId);719 }720 /**721 * Check running in foreground application by bundleId or appId722 *723 * @param bundleId the bundle identifier for iOS (or appPackage for Android) of the app to query the state of.724 * @return boolean725 */726 default public boolean isAppRunning(String bundleId) {727 ApplicationState actualApplicationState = ((MobileDriver<?>) castDriver()).queryAppState(bundleId);728 return ApplicationState.RUNNING_IN_FOREGROUND.equals(actualApplicationState);729 }730 /**731 * Terminate running driver/application732 */733 default public void terminateApp() {734 String bundleId = "";735 String os = getDevice().getOs();736 // get bundleId or appId of the application started by driver737 if (os.equalsIgnoreCase(SpecialKeywords.ANDROID)) {738 bundleId = ((AppiumDriver<?>) castDriver()).getSessionDetail(SpecialKeywords.APP_PACKAGE).toString();739 } else if (os.equalsIgnoreCase(SpecialKeywords.IOS) || os.equalsIgnoreCase(SpecialKeywords.MAC) || os.equalsIgnoreCase(SpecialKeywords.TVOS)) {740 bundleId = ((AppiumDriver<?>) castDriver()).getSessionDetail(SpecialKeywords.BUNDLE_ID).toString();741 }742 terminateApp(bundleId);743 }744 /**745 * Terminate running application by bundleId or appId746 *747 * @param bundleId the bundle identifier for iOS (or appPackage for Android) of the app to terminate.748 */749 default public void terminateApp(String bundleId) {750 ((MobileDriver<?>) castDriver()).terminateApp(bundleId);751 }752 753 /**754 * The application that has its package name set to current driver's755 * capabilities will be closed to background IN CASE IT IS CURRENTLY IN756 * FOREGROUND. Will be in recent app's list;757 */758 default public void closeApp() {759 UTILS_LOGGER.info("Application will be closed to background");760 ((MobileDriver<?>) castDriver()).closeApp();761 }762 /**763 * Cast Carina driver to WebDriver removing all extra listeners (try to avoid direct operations via WebDriver as it doesn't support logging etc)764 *765 * @return WebDriver766 */767 default public WebDriver castDriver() {768 WebDriver drv = getDriver();769 if (drv instanceof EventFiringWebDriver) {770 drv = ((EventFiringWebDriver) drv).getWrappedDriver();771 }772 return drv;773 }774 // TODO Update this method using findByImage strategy775 /**776 * Pressing bottom right button on the keyboard by coordinates: "search", "ok",777 * "next", etc. - various keys appear at this position. Tested at Nexus 6P778 * Android 8.0.0 standard keyboard. Coefficients of coordinates for other779 * devices and custom keyboards could be different.780 */781 @SuppressWarnings("rawtypes")782 default public void pressBottomRightKey() {783 WebDriver driver = castDriver();784 Dimension size = helper.performIgnoreException(() -> driver.manage().window().getSize());785 int height = size.getHeight();786 int width = size.getWidth();787 PointOption<?> option = PointOption.point((int) (width * 0.915), (int) (height * 0.945));788 new TouchAction((MobileDriver<?>) castDriver()).tap(option).perform();789 }790 default public boolean isChecked(final ExtendedWebElement element) {791 // TODO: SZ migrate to FluentWaits792 return element.isElementPresent(5)793 && (element.getElement().isSelected() || element.getAttribute("checked").equals("true"));794 }795 /**796 * If the application you're interested about is installed - returns "true".797 * Otherwise, returns "false".798 *799 * @param packageName800 * - app's package or bundle id801 * 802 * @return boolean803 */804 default public boolean isApplicationInstalled(String packageName) {805 boolean installed = ((MobileDriver<?>) castDriver()).isAppInstalled(packageName);806 UTILS_LOGGER.info(String.format("Application by package name (%s) installed: ", packageName) + installed);807 return installed;808 }809 /**810 * Method to launch Android application by its package name.811 *812 * Application should be installed to device.813 *814 * Application might not be running in background, but will be launched anyway.815 *816 * @param packageName817 * - app's package or bundle id818 */819 default public void startApp(String packageName) {820 UTILS_LOGGER.info("Starting " + packageName);821 ((MobileDriver<?>) castDriver()).activateApp(packageName);822 }823 /**824 * Will install application if path to apk-file on working machine is set.825 *826 * @param apkPath String827 */828 default public void installApp(String apkPath) {829 UTILS_LOGGER.info("Will install application with apk-file from " + apkPath);830 ((MobileDriver<?>) castDriver()).installApp(apkPath);831 }832 /**833 * To remove installed application by provided package name834 *835 * @param packageName836 * - app's package or bundle id837 *838 * @return true if succeed839 */840 default public boolean removeApp(String packageName) {841 boolean removed = ((MobileDriver<?>) castDriver()).removeApp(packageName);842 UTILS_LOGGER.info(String.format("Application (%s) is successfuly removed: ", packageName) + removed);843 return removed;844 }845 /**846 * Method to reset test application.847 *848 * App's settings will be reset. User will be logged out. Application will be849 * closed to background.850 */851 default public void clearAppCache() {852 UTILS_LOGGER.info("Initiation application reset...");853 ((MobileDriver<?>) castDriver()).resetApp();854 }855}...
Source:Tapping.java
...57 public void tap(int startx, int starty, int duration) {58 // TODO: add Screenshot.capture()59 try {60 @SuppressWarnings("rawtypes")61 TouchAction touchAction = new TouchAction((MobileDriver<?>) castDriver());62 PointOption<?> startPoint = PointOption.point(startx, starty);63 WaitOptions waitOptions = WaitOptions.waitOptions(Duration.ofMillis(duration));6465 if (duration == 0) {66 // do not perform waiter as using 6.0.0. appium java client we do longpress instead of simple tap even with 0 wait duration67 touchAction.press(startPoint).release().perform();68 } else {69 touchAction.press(startPoint).waitAction(waitOptions).release().perform();70 }71 Messager.TAP_EXECUTED.info(String.valueOf(startx), String.valueOf(starty));72 } catch (Exception e) {73 Messager.TAP_NOT_EXECUTED.error(String.valueOf(startx), String.valueOf(starty));74 throw e;75 }
...
castDriver
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5public class castDriver {6 public static void main(String[] args) {7 WebDriver driver = new ChromeDriver();8 ExtendedWebElement element = (ExtendedWebElement) driver.findElement(By.name("q"));9 System.out.println(element.getDriver());10 driver.quit();11 }12}13import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;14import org.openqa.selenium.By;15import org.openqa.selenium.WebDriver;16import org.openqa.selenium.chrome.ChromeDriver;17import org.openqa.selenium.support.ui.WebDriverWait;18public class castDriver {19 public static void main(String[] args) {20 WebDriver driver = new ChromeDriver();21 ExtendedWebElement element = (ExtendedWebElement) driver.findElement(By.name("q"));22 System.out.println(element.getDriver());23 WebDriverWait wait = new WebDriverWait(driver, 10);24 System.out.println(wait);25 driver.quit();26 }27}
castDriver
Using AI Code Generation
1package com.qaprosoft.carina.demo.gui.components;2import java.util.List;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.FindBy;6import org.openqa.selenium.support.FindBys;7import org.openqa.selenium.support.How;8import org.openqa.selenium.support.ui.ExpectedConditions;9import org.openqa.selenium.support.ui.WebDriverWait;10import org.testng.Assert;11import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;12import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElementDecorator;13import com.qaprosoft.carina.core.foundation.webdriver.decorator.FinderFactory;14import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageFactory;15import com.qaprosoft.carina.core.foundation.webdriver.decorator.TypeCastable;16import com.qaprosoft.carina.core.foundation.webdriver.decorator.TypeCastableElement;17import com.qaprosoft.carina.core.foundation.webdriver.decorator.TypeCastableList;18import com.qaprosoft.carina.core.foundation.webdriver.decorator.TypeCastableWebDriver;19import io.appium.java_client.AppiumDriver;20import io.appium.java_client.MobileElement;21import io.appium.java_client.android.AndroidDriver;22import io.appium.java_client.pagefactory.AndroidFindBy;23import io.appium.java_client.pagefactory.AndroidFindBySet;24import io.appium.java_client.pagefactory.AndroidFindBys;25import io.appium.java_client.pagefactory.AndroidFindBysSet;26import io.appium.java_client.pagefactory.AndroidFindAll;27import io.appium.java_client.pagefactory.AndroidFindAllSet;28import io.appium.java_client.pagefactory.AndroidFindAllSets;29import io.appium.java_client.pagefactory.AndroidFindAlls;30import io.appium.java_client.pagefactory.AndroidFindBysSets;31import io.appium.java_client.pagefactory.AndroidFindAllSets;32import io.appium.java_client.pagefactory.AndroidFindBySets;33import io.appium.java_client.pagefactory.iOSFindBy;34import io.appium.java_client.pagefactory.iOSFindBySet;35import io.appium.java_client.pagefactory.iOSFindBys;36import io.appium.java_client.pagefactory.iOSFindBysSet;37import io.appium.java_client.pagefactory.iOSFindAll;38import io.appium.java_client.pagefactory.iOSFindAllSet;39import io.appium.java_client.pagefactory.iOSFindAllSets;40import io.appium.java_client.pagefactory.iOSFindAlls;41import io.appium.java_client.pagefactory.iOSFindBysSets;42import io.appium.java_client.page
castDriver
Using AI Code Generation
1ExtendedWebElement castedElement = new ExtendedWebElement(element);2castedElement.castDriver(WebDriver.class);3ExtendedWebElement castedElement = new ExtendedWebElement(element);4castedElement.castDriver(WebDriver.class);5ExtendedWebElement castedElement = new ExtendedWebElement(element);6castedElement.castDriver(WebDriver.class);7ExtendedWebElement castedElement = new ExtendedWebElement(element);8castedElement.castDriver(WebDriver.class);9ExtendedWebElement castedElement = new ExtendedWebElement(element);10castedElement.castDriver(WebDriver.class);11ExtendedWebElement castedElement = new ExtendedWebElement(element);12castedElement.castDriver(WebDriver.class);13ExtendedWebElement castedElement = new ExtendedWebElement(element);14castedElement.castDriver(WebDriver.class);15ExtendedWebElement castedElement = new ExtendedWebElement(element);16castedElement.castDriver(WebDriver.class);17ExtendedWebElement castedElement = new ExtendedWebElement(element);18castedElement.castDriver(WebDriver.class);19ExtendedWebElement castedElement = new ExtendedWebElement(element);20castedElement.castDriver(WebDriver.class);21ExtendedWebElement castedElement = new ExtendedWebElement(element);22castedElement.castDriver(WebDriver.class);23ExtendedWebElement castedElement = new ExtendedWebElement(element);24castedElement.castDriver(WebDriver.class);
castDriver
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.remote.RemoteWebDriver;5import org.openqa.selenium.support.FindBy;6import org.openqa.selenium.support.PageFactory;7public class 1 {8 private ExtendedWebElement searchBox;9 public static void main(String[] args) {10 WebDriver driver = new ChromeDriver();11 1 test = new 1();12 PageFactory.initElements(driver, test);13 test.searchBox.click();14 RemoteWebDriver remoteWebDriver = ExtendedWebElement.castDriver(driver);15 System.out.println(remoteWebDriver.getClass());16 }17}18import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;19import org.openqa.selenium.WebDriver;20import org.openqa.selenium.chrome.ChromeDriver;21import org.openqa.selenium.remote.RemoteWebDriver;22import org.openqa.selenium.support.FindBy;23import org.openqa.selenium.support.PageFactory;24public class 2 {25 private ExtendedWebElement searchBox;26 public static void main(String[] args) {27 WebDriver driver = new ChromeDriver();28 2 test = new 2();29 PageFactory.initElements(driver, test);30 test.searchBox.click();31 RemoteWebDriver remoteWebDriver = ExtendedWebElement.castDriver(driver);32 System.out.println(remoteWebDriver.getClass());33 }34}35import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;36import org.openqa.selenium.WebDriver;37import org.openqa.selenium.chrome.ChromeDriver;38import org.openqa.selenium.remote.RemoteWebDriver;39import org.openqa.selenium.support.FindBy;40import org.openqa.selenium.support.PageFactory;41public class 3 {
castDriver
Using AI Code Generation
1package com.qaprosoft.carina.demo.gui.components;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.support.FindBy;5import org.openqa.selenium.support.ui.ExpectedConditions;6import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;7import com.qaprosoft.carina.core.gui.AbstractUIObject;8public class FooterMenu extends AbstractUIObject {9 private ExtendedWebElement homeBtn;10 private ExtendedWebElement aboutBtn;11 private ExtendedWebElement contactBtn;12 public FooterMenu(WebDriver driver, WebElement el) {13 super(driver, el);14 }15 public void clickHomeBtn() {16 homeBtn.click();17 }18 public void clickAboutBtn() {19 aboutBtn.click();20 }21 public void clickContactBtn() {22 contactBtn.click();23 }24 public boolean isPageOpened() {25 return getDriver().waitUntil(ExpectedConditions.visibilityOf(el)).isDisplayed();26 }27}28package com.qaprosoft.carina.demo.gui.pages;29import org.openqa.selenium.WebDriver;30import org.openqa.selenium.support.FindBy;31import org.openqa.selenium.support.ui.ExpectedConditions;32import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;33import com.qaprosoft.carina.core.gui.AbstractPage;34import com.qaprosoft.carina.demo.gui.components.FooterMenu;35public class ContactPage extends AbstractPage {36 private FooterMenu footerMenu;37 public ContactPage(WebDriver driver) {38 super(driver);39 }40 public void clickHomeBtn() {41 footerMenu.clickHomeBtn();42 }43 public void clickAboutBtn()
castDriver
Using AI Code Generation
1AndroidDriver<AndroidElement> driver = element.castDriver(AndroidDriver.class);2AndroidElement androidElement = element.castElement(AndroidElement.class);3androidElement.click();4AndroidDriver<AndroidElement> driver = element.castDriver(AndroidDriver.class);5AndroidElement androidElement = element.castElement(AndroidElement.class);6androidElement.click();7AndroidDriver<AndroidElement> driver = element.castDriver(AndroidDriver.class);
castDriver
Using AI Code Generation
1package com.qaprosoft.carina.demo;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.support.FindBy;4import org.testng.annotations.Test;5import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;6import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;7import com.qaprosoft.carina.core.gui.AbstractPage;8public class castDriver extends AbstractPage {9 private WebElement login;10 public castDriver() {11 super(PageOpeningStrategy.BY_ELEMENT);12 }13 public void castDriver() {14 ExtendedWebElement castLogin = ExtendedWebElement.castDriver(login);15 String attribute = castLogin.getAttribute("class");16 System.out.println(attribute);17 }18}19package com.qaprosoft.carina.demo;20import org.openqa.selenium.WebElement;21import org.openqa.selenium.support.FindBy;22import org.testng.annotations.Test;23import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;24import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;25import com.qaprosoft.carina.core.gui.AbstractPage;26public class castDriver extends AbstractPage {27 private WebElement login;28 public castDriver() {29 super(PageOpeningStrategy.BY_ELEMENT);30 }31 public void castDriver() {32 ExtendedWebElement castLogin = ExtendedWebElement.castDriver(login);33 String text = castLogin.getText();34 System.out.println(text);35 }36}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!