diff --git a/pom.xml b/pom.xml index 013ff7302..0f941bb46 100644 --- a/pom.xml +++ b/pom.xml @@ -15,7 +15,9 @@ ~ limitations under the License. --> - + 4.0.0 io.appium @@ -75,7 +77,8 @@ https://github.com/appium/java-client scm:git:ssh://git@github.com/appium/java-client.git - scm:git:ssh://git@github.com/appium/java-client.git + scm:git:ssh://git@github.com/appium/java-client.git + HEAD @@ -208,6 +211,19 @@ + + org.apache.maven.plugins + maven-eclipse-plugin + 2.10 + + true + true + ${basedir} + + https://google-styleguide.googlecode.com/svn/trunk/eclipse-java-google-style.xml + + + diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index 88b8ff6ab..ba2215850 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -29,6 +29,7 @@ import org.openqa.selenium.html5.Location; import org.openqa.selenium.remote.*; import org.openqa.selenium.remote.html5.RemoteLocationContext; +import org.openqa.selenium.remote.http.HttpClient; import org.openqa.selenium.remote.http.HttpMethod; import javax.xml.bind.DatatypeConverter; @@ -39,116 +40,111 @@ import java.util.Set; import static io.appium.java_client.MobileCommand.*; -import org.openqa.selenium.remote.http.HttpClient; /** * @param the required type of class which implement {@link org.openqa.selenium.WebElement}. - * Instances of the defined type will be returned via findElement* and findElements*. - * Warning (!!!). Allowed types: - * {@link org.openqa.selenium.WebElement} - * {@link io.appium.java_client.TouchableElement} - * {@link org.openqa.selenium.remote.RemoteWebElement} - * {@link io.appium.java_client.MobileElement} and its subclasses that designed specifically for each target mobile OS (still Android and iOS) + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} and its subclasses that designed specifically for each target mobile OS (still Android and iOS) */ @SuppressWarnings("unchecked") -public abstract class AppiumDriver extends DefaultGenericMobileDriver { - - private final static ErrorHandler errorHandler = new ErrorHandler( - new ErrorCodesMobile(), true); - private URL remoteAddress; - private RemoteLocationContext locationContext; - private ExecuteMethod executeMethod; +public abstract class AppiumDriver + extends DefaultGenericMobileDriver { + private final static ErrorHandler errorHandler = new ErrorHandler(new ErrorCodesMobile(), true); // frequently used command parameters protected final String KEY_CODE = "keycode"; protected final String PATH = "path"; private final String SETTINGS = "settings"; - private final String LANGUAGE_PARAM = "language"; private final String STRING_FILE_PARAM = "stringFile"; + private URL remoteAddress; + private RemoteLocationContext locationContext; + private ExecuteMethod executeMethod; - /** - * @param originalCapabilities - * the given {@link Capabilities} - * @param newPlatform - * a {@link MobileCapabilityType#PLATFORM_NAME} value which has - * to be set up - * @return {@link Capabilities} with changed mobile platform value - */ - protected static Capabilities substituteMobilePlatform( - Capabilities originalCapabilities, String newPlatform) { - DesiredCapabilities dc = new DesiredCapabilities(originalCapabilities); - dc.setCapability(MobileCapabilityType.PLATFORM_NAME, newPlatform); - return dc; - } - - @Override - public List findElements(By by){ - return super.findElements(by); + private AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities) { + super(executor, capabilities); + this.executeMethod = new AppiumExecutionMethod(this); + locationContext = new RemoteLocationContext(executeMethod); + super.setErrorHandler(errorHandler); + this.remoteAddress = executor.getAddressOfRemoteServer(); } - @Override - public List findElementsById(String id){ - return super.findElementsById(id); + public AppiumDriver(URL remoteAddress, Capabilities desiredCapabilities) { + this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress), + desiredCapabilities); } - public List findElementsByLinkText(String using) { - return super.findElementsByLinkText(using); + public AppiumDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress, + httpClientFactory), desiredCapabilities); } - public List findElementsByPartialLinkText(String using) { - return super.findElementsByPartialLinkText(using); + public AppiumDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities) { + this(new AppiumCommandExecutor(MobileCommand.commandRepository, service), + desiredCapabilities); } - public List findElementsByTagName(String using) { - return super.findElementsByTagName(using); + public AppiumDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + this(new AppiumCommandExecutor(MobileCommand.commandRepository, service, httpClientFactory), + desiredCapabilities); } - public List findElementsByName(String using) { - return super.findElementsByName(using); + public AppiumDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities) { + this(builder.build(), desiredCapabilities); } - public List findElementsByClassName(String using) { - return super.findElementsByClassName(using); + public AppiumDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + this(builder.build(), httpClientFactory, desiredCapabilities); } - public List findElementsByCssSelector(String using) { - return super.findElementsByCssSelector(using); + public AppiumDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { + this(AppiumDriverLocalService.buildDefaultService(), httpClientFactory, + desiredCapabilities); } - public List findElementsByXPath(String using) { - return super.findElementsByXPath(using); + public AppiumDriver(Capabilities desiredCapabilities) { + this(AppiumDriverLocalService.buildDefaultService(), desiredCapabilities); } - @Override - public List findElementsByAccessibilityId(String using) { - return (List) findElements("accessibility id", using); + /** + * @param originalCapabilities the given {@link Capabilities} + * @param newPlatform a {@link MobileCapabilityType#PLATFORM_NAME} value which has + * to be set up + * @return {@link Capabilities} with changed mobile platform value + */ + protected static Capabilities substituteMobilePlatform(Capabilities originalCapabilities, + String newPlatform) { + DesiredCapabilities dc = new DesiredCapabilities(originalCapabilities); + dc.setCapability(MobileCapabilityType.PLATFORM_NAME, newPlatform); + return dc; } /** - * @param param - * is a parameter name - * @param value - * is the parameter value + * @param param is a parameter name + * @param value is the parameter value * @return built {@link ImmutableMap} */ - protected static ImmutableMap getCommandImmutableMap( - String param, Object value) { + protected static ImmutableMap getCommandImmutableMap(String param, + Object value) { ImmutableMap.Builder builder = ImmutableMap.builder(); builder.put(param, value); return builder.build(); } /** - * - * @param params - * is the array with parameter names - * @param values - * is the array with parameter values + * @param params is the array with parameter names + * @param values is the array with parameter values * @return built {@link ImmutableMap} */ - protected static ImmutableMap getCommandImmutableMap( - String[] params, Object[] values) { + protected static ImmutableMap getCommandImmutableMap(String[] params, + Object[] values) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (int i = 0; i < params.length; i++) { if (_isNotNullOrEmpty(params[i]) && _isNotNullOrEmpty(values[i])) { @@ -158,75 +154,84 @@ protected static ImmutableMap getCommandImmutableMap( return builder.build(); } - private AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities){ - super(executor, capabilities); - this.executeMethod = new AppiumExecutionMethod(this); - locationContext = new RemoteLocationContext(executeMethod); - super.setErrorHandler(errorHandler); - this.remoteAddress = executor.getAddressOfRemoteServer(); + @SuppressWarnings("unused") private static CommandInfo deleteC(String url) { + return new CommandInfo(url, HttpMethod.DELETE); } - - public AppiumDriver(URL remoteAddress, Capabilities desiredCapabilities) { - this(new AppiumCommandExecutor( - MobileCommand.commandRepository, remoteAddress), desiredCapabilities); + + /** + * Checks if a string is null, empty, or whitespace. + * + * @param str String to check. + * @return True if str is not null or empty. + */ + protected static boolean _isNotNullOrEmpty(String str) { + return str != null && !str.isEmpty() && str.trim().length() > 0; } - public AppiumDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - this(new AppiumCommandExecutor( - MobileCommand.commandRepository, remoteAddress, httpClientFactory), desiredCapabilities); + protected static boolean _isNotNullOrEmpty(Object ob) { + return ob != null; } - public AppiumDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities) { - this(new AppiumCommandExecutor( - MobileCommand.commandRepository, service), desiredCapabilities); + @Override public List findElements(By by) { + return super.findElements(by); } - - public AppiumDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - this(new AppiumCommandExecutor( - MobileCommand.commandRepository, service, httpClientFactory), desiredCapabilities); + + @Override public List findElementsById(String id) { + return super.findElementsById(id); } - public AppiumDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities) { - this(builder.build(), desiredCapabilities); + public List findElementsByLinkText(String using) { + return super.findElementsByLinkText(using); } - - public AppiumDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - this(builder.build(), httpClientFactory, desiredCapabilities); + + public List findElementsByPartialLinkText(String using) { + return super.findElementsByPartialLinkText(using); } - - public AppiumDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - this(AppiumDriverLocalService.buildDefaultService(), httpClientFactory, desiredCapabilities); + + public List findElementsByTagName(String using) { + return super.findElementsByTagName(using); } - - public AppiumDriver(Capabilities desiredCapabilities) { - this(AppiumDriverLocalService.buildDefaultService(), desiredCapabilities); + + public List findElementsByName(String using) { + return super.findElementsByName(using); + } + + public List findElementsByClassName(String using) { + return super.findElementsByClassName(using); + } + + public List findElementsByCssSelector(String using) { + return super.findElementsByCssSelector(using); } - @Override - protected Response execute(String command) { + public List findElementsByXPath(String using) { + return super.findElementsByXPath(using); + } + + @Override public List findElementsByAccessibilityId(String using) { + return (List) findElements("accessibility id", using); + } + + @Override protected Response execute(String command) { return super.execute(command, ImmutableMap.of()); } - @Override - public ExecuteMethod getExecuteMethod() { + @Override public ExecuteMethod getExecuteMethod() { return executeMethod; } /** * @see InteractsWithApps#resetApp() */ - @Override - public void resetApp() { + @Override public void resetApp() { execute(MobileCommand.RESET); } /** * @see InteractsWithApps#isAppInstalled(String) */ - @Override - public boolean isAppInstalled(String bundleId) { - Response response = execute(IS_APP_INSTALLED, - ImmutableMap.of("bundleId", bundleId)); + @Override public boolean isAppInstalled(String bundleId) { + Response response = execute(IS_APP_INSTALLED, ImmutableMap.of("bundleId", bundleId)); return Boolean.parseBoolean(response.getValue().toString()); } @@ -234,48 +239,42 @@ public boolean isAppInstalled(String bundleId) { /** * @see InteractsWithApps#installApp(String) */ - @Override - public void installApp(String appPath) { + @Override public void installApp(String appPath) { execute(INSTALL_APP, ImmutableMap.of("appPath", appPath)); } /** * @see InteractsWithApps#removeApp(String) */ - @Override - public void removeApp(String bundleId) { + @Override public void removeApp(String bundleId) { execute(REMOVE_APP, ImmutableMap.of("bundleId", bundleId)); } /** * @see InteractsWithApps#launchApp() */ - @Override - public void launchApp() { + @Override public void launchApp() { execute(LAUNCH_APP); } /** * @see InteractsWithApps#closeApp() */ - @Override - public void closeApp() { + @Override public void closeApp() { execute(CLOSE_APP); } /** * @see InteractsWithApps#runAppInBackground(int) */ - @Override - public void runAppInBackground(int seconds) { + @Override public void runAppInBackground(int seconds) { execute(RUN_APP_IN_BACKGROUND, ImmutableMap.of("seconds", seconds)); } /** * @see DeviceActionShortcuts#getDeviceTime() */ - @Override - public String getDeviceTime() { + @Override public String getDeviceTime() { Response response = execute(GET_DEVICE_TIME); return response.getValue().toString(); } @@ -283,18 +282,15 @@ public String getDeviceTime() { /** * @see DeviceActionShortcuts#hideKeyboard() */ - @Override - public void hideKeyboard() { + @Override public void hideKeyboard() { execute(HIDE_KEYBOARD); } /** * @see InteractsWithFiles#pullFile(String) */ - @Override - public byte[] pullFile(String remotePath) { - Response response = execute(PULL_FILE, - ImmutableMap.of(PATH, remotePath)); + @Override public byte[] pullFile(String remotePath) { + Response response = execute(PULL_FILE, ImmutableMap.of(PATH, remotePath)); String base64String = response.getValue().toString(); return DatatypeConverter.parseBase64Binary(base64String); @@ -303,10 +299,8 @@ public byte[] pullFile(String remotePath) { /** * @see InteractsWithFiles#pullFolder(String) */ - @Override - public byte[] pullFolder(String remotePath) { - Response response = execute(PULL_FOLDER, - ImmutableMap.of(PATH, remotePath)); + @Override public byte[] pullFolder(String remotePath) { + Response response = execute(PULL_FOLDER, ImmutableMap.of(PATH, remotePath)); String base64String = response.getValue().toString(); return DatatypeConverter.parseBase64Binary(base64String); @@ -315,11 +309,9 @@ public byte[] pullFolder(String remotePath) { /** * @see PerformsTouchActions#performTouchAction(TouchAction) */ - @SuppressWarnings("rawtypes") - @Override - public TouchAction performTouchAction(TouchAction touchAction) { - ImmutableMap parameters = touchAction - .getParameters(); + @SuppressWarnings("rawtypes") @Override public TouchAction performTouchAction( + TouchAction touchAction) { + ImmutableMap parameters = touchAction.getParameters(); touchAction.clearParameters(); execute(PERFORM_TOUCH_ACTION, parameters); @@ -329,19 +321,16 @@ public TouchAction performTouchAction(TouchAction touchAction) { /** * @see PerformsTouchActions#performMultiTouchAction(MultiTouchAction) */ - @Override - @SuppressWarnings({ "rawtypes"}) - public void performMultiTouchAction(MultiTouchAction multiAction) { - ImmutableMap parameters = multiAction - .getParameters(); + @Override @SuppressWarnings({"rawtypes"}) public void performMultiTouchAction( + MultiTouchAction multiAction) { + ImmutableMap parameters = multiAction.getParameters(); execute(PERFORM_MULTI_TOUCH, parameters); } /** * @see TouchShortcuts#tap(int, WebElement, int) */ - @Override - public void tap(int fingers, WebElement element, int duration) { + @Override public void tap(int fingers, WebElement element, int duration) { MultiTouchAction multiTouch = new MultiTouchAction(this); for (int i = 0; i < fingers; i++) { @@ -354,8 +343,7 @@ public void tap(int fingers, WebElement element, int duration) { /** * @see TouchShortcuts#tap(int, int, int, int) */ - @Override - public void tap(int fingers, int x, int y, int duration) { + @Override public void tap(int fingers, int x, int y, int duration) { MultiTouchAction multiTouch = new MultiTouchAction(this); for (int i = 0; i < fingers; i++) { @@ -368,130 +356,136 @@ public void tap(int fingers, int x, int y, int duration) { /** * @see TouchShortcuts#swipe(int, int, int, int, int) */ - @Override - public void swipe(int startx, int starty, int endx, int endy, int duration) { + @Override public void swipe(int startx, int starty, int endx, int endy, int duration) { TouchAction touchAction = new TouchAction(this); // appium converts press-wait-moveto-release to a swipe action - touchAction.press(startx, starty).waitAction(duration) - .moveTo(endx, endy).release(); + touchAction.press(startx, starty).waitAction(duration).moveTo(endx, endy).release(); touchAction.perform(); } - /** - * Convenience method for pinching an element on the screen. - * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. - * NOTE: - * This convenience method places the initial touches around the element, if this would happen to place one of them - * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param el The element to pinch - */ - public void pinch(WebElement el) { - MultiTouchAction multiTouch = new MultiTouchAction(this); - - Dimension dimensions = el.getSize(); - Point upperLeft = el.getLocation(); - Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, upperLeft.getY() + dimensions.getHeight() / 2); - int yOffset = center.getY() - upperLeft.getY(); - - TouchAction action0 = new TouchAction(this).press(el, center.getX(), center.getY() - yOffset).moveTo(el).release(); - TouchAction action1 = new TouchAction(this).press(el, center.getX(), center.getY() + yOffset).moveTo(el).release(); - - multiTouch.add(action0).add(action1); - - multiTouch.perform(); - } - - /** - * Convenience method for pinching an element on the screen. - * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. - * NOTE: - * This convenience method places the initial touches around the element at a distance, if this would happen to place - * one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the - * MultiTouchAction api instead of this method. - * - * @param x x coordinate to terminate the pinch on - * @param y y coordinate to terminate the pinch on - */ - public void pinch(int x, int y) { - MultiTouchAction multiTouch = new MultiTouchAction(this); - - int scrHeight = manage().window().getSize().getHeight(); - int yOffset = 100; - - if (y - 100 < 0) { - yOffset = y; - } else if (y + 100 > scrHeight) { - yOffset = scrHeight - y; - } - - TouchAction action0 = new TouchAction(this).press(x, y - yOffset).moveTo(x, y).release(); - TouchAction action1 = new TouchAction(this).press(x, y + yOffset).moveTo(x, y).release(); - - multiTouch.add(action0).add(action1); - - multiTouch.perform(); - } - - /** - * Convenience method for "zooming in" on an element on the screen. - * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. - * NOTE: - * This convenience method slides touches away from the element, if this would happen to place one of them - * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param el The element to pinch - */ - public void zoom(WebElement el) { - MultiTouchAction multiTouch = new MultiTouchAction(this); - - Dimension dimensions = el.getSize(); - Point upperLeft = el.getLocation(); - Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, upperLeft.getY() + dimensions.getHeight() / 2); - int yOffset = center.getY() - upperLeft.getY(); - - TouchAction action0 = new TouchAction(this).press(center.getX(), center.getY()).moveTo(el, center.getX(), center.getY() - yOffset).release(); - TouchAction action1 = new TouchAction(this).press(center.getX(), center.getY()).moveTo(el, center.getX(), center.getY() + yOffset).release(); - - multiTouch.add(action0).add(action1); - - multiTouch.perform(); - } - - /** - * Convenience method for "zooming in" on an element on the screen. - * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. - * NOTE: - * This convenience method slides touches away from the element, if this would happen to place one of them - * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param x x coordinate to start zoom on - * @param y y coordinate to start zoom on - */ - public void zoom(int x, int y) { - MultiTouchAction multiTouch = new MultiTouchAction(this); - - int scrHeight = manage().window().getSize().getHeight(); - int yOffset = 100; - - if (y - 100 < 0) { - yOffset = y; - } else if (y + 100 > scrHeight) { - yOffset = scrHeight - y; - } - - TouchAction action0 = new TouchAction(this).press(x, y).moveTo(0, -yOffset).release(); - TouchAction action1 = new TouchAction(this).press(x, y).moveTo(0, yOffset).release(); - - multiTouch.add(action0).add(action1); - - multiTouch.perform(); - } + /** + * Convenience method for pinching an element on the screen. + * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. + * NOTE: + * This convenience method places the initial touches around the element, if this would happen to place one of them + * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param el The element to pinch + */ + public void pinch(WebElement el) { + MultiTouchAction multiTouch = new MultiTouchAction(this); + + Dimension dimensions = el.getSize(); + Point upperLeft = el.getLocation(); + Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, + upperLeft.getY() + dimensions.getHeight() / 2); + int yOffset = center.getY() - upperLeft.getY(); + + TouchAction action0 = + new TouchAction(this).press(el, center.getX(), center.getY() - yOffset).moveTo(el) + .release(); + TouchAction action1 = + new TouchAction(this).press(el, center.getX(), center.getY() + yOffset).moveTo(el) + .release(); + + multiTouch.add(action0).add(action1); + + multiTouch.perform(); + } + + /** + * Convenience method for pinching an element on the screen. + * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. + * NOTE: + * This convenience method places the initial touches around the element at a distance, if this would happen to place + * one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the + * MultiTouchAction api instead of this method. + * + * @param x x coordinate to terminate the pinch on + * @param y y coordinate to terminate the pinch on + */ + public void pinch(int x, int y) { + MultiTouchAction multiTouch = new MultiTouchAction(this); + + int scrHeight = manage().window().getSize().getHeight(); + int yOffset = 100; + + if (y - 100 < 0) { + yOffset = y; + } else if (y + 100 > scrHeight) { + yOffset = scrHeight - y; + } + + TouchAction action0 = new TouchAction(this).press(x, y - yOffset).moveTo(x, y).release(); + TouchAction action1 = new TouchAction(this).press(x, y + yOffset).moveTo(x, y).release(); + + multiTouch.add(action0).add(action1); + + multiTouch.perform(); + } + + /** + * Convenience method for "zooming in" on an element on the screen. + * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. + * NOTE: + * This convenience method slides touches away from the element, if this would happen to place one of them + * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param el The element to pinch + */ + public void zoom(WebElement el) { + MultiTouchAction multiTouch = new MultiTouchAction(this); + + Dimension dimensions = el.getSize(); + Point upperLeft = el.getLocation(); + Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, + upperLeft.getY() + dimensions.getHeight() / 2); + int yOffset = center.getY() - upperLeft.getY(); + + TouchAction action0 = new TouchAction(this).press(center.getX(), center.getY()) + .moveTo(el, center.getX(), center.getY() - yOffset).release(); + TouchAction action1 = new TouchAction(this).press(center.getX(), center.getY()) + .moveTo(el, center.getX(), center.getY() + yOffset).release(); + + multiTouch.add(action0).add(action1); + + multiTouch.perform(); + } + + /** + * Convenience method for "zooming in" on an element on the screen. + * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. + * NOTE: + * This convenience method slides touches away from the element, if this would happen to place one of them + * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param x x coordinate to start zoom on + * @param y y coordinate to start zoom on + */ + public void zoom(int x, int y) { + MultiTouchAction multiTouch = new MultiTouchAction(this); + + int scrHeight = manage().window().getSize().getHeight(); + int yOffset = 100; + + if (y - 100 < 0) { + yOffset = y; + } else if (y + 100 > scrHeight) { + yOffset = scrHeight - y; + } + + TouchAction action0 = new TouchAction(this).press(x, y).moveTo(0, -yOffset).release(); + TouchAction action1 = new TouchAction(this).press(x, y).moveTo(0, yOffset).release(); + + multiTouch.add(action0).add(action1); + + multiTouch.perform(); + } /** * Get settings stored for this test session It's probably better to use a @@ -504,8 +498,7 @@ public JsonObject getSettings() { Response response = execute(GET_SETTINGS); JsonParser parser = new JsonParser(); - JsonObject settings = (JsonObject) parser.parse(response.getValue() - .toString()); + JsonObject settings = (JsonObject) parser.parse(response.getValue().toString()); return settings; } @@ -515,8 +508,7 @@ public JsonObject getSettings() { * convenience function, rather than use this function directly. Try finding * the method for the specific setting you want to change * - * @param settings - * Map of setting keys and values + * @param settings Map of setting keys and values */ private void setSettings(ImmutableMap settings) { execute(SET_SETTINGS, getCommandImmutableMap(SETTINGS, settings)); @@ -527,16 +519,13 @@ private void setSettings(ImmutableMap settings) { * convenience function, rather than use this function directly. Try finding * the method for the specific setting you want to change * - * @param setting - * AppiumSetting you wish to set - * @param value - * value of the setting + * @param setting AppiumSetting you wish to set + * @param value value of the setting */ protected void setSetting(AppiumSetting setting, Object value) { setSettings(getCommandImmutableMap(setting.toString(), value)); } - @Deprecated /** * This method works incorrectly. It is deprecated and it is going to be removed further. @@ -544,13 +533,11 @@ protected void setSetting(AppiumSetting setting, Object value) { * * Since Appium node 1.5.x you are free to use * IOSDriver.lockDevice(int seconds) or AndroidDriver.lockDevice()...AndroidDriver.unlockDevice() instead - */ - public void lockScreen(int seconds) { + */ public void lockScreen(int seconds) { execute(LOCK, ImmutableMap.of("seconds", seconds)); } - @Override - public WebDriver context(String name) { + @Override public WebDriver context(String name) { if (!_isNotNullOrEmpty(name)) { throw new IllegalArgumentException("Must supply a context name"); } @@ -559,8 +546,7 @@ public WebDriver context(String name) { return AppiumDriver.this; } - @Override - public Set getContextHandles() { + @Override public Set getContextHandles() { Response response = execute(DriverCommand.GET_CONTEXT_HANDLES); Object value = response.getValue(); try { @@ -568,29 +554,25 @@ public Set getContextHandles() { return new LinkedHashSet(returnedValues); } catch (ClassCastException ex) { throw new WebDriverException( - "Returned value cannot be converted to List: " - + value, ex); + "Returned value cannot be converted to List: " + value, ex); } } - @Override - public String getContext() { - String contextName = String.valueOf(execute( - DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue()); + @Override public String getContext() { + String contextName = + String.valueOf(execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue()); if (contextName.equals("null")) { return null; } return contextName; } - @Override - public void rotate(ScreenOrientation orientation) { - execute(DriverCommand.SET_SCREEN_ORIENTATION, ImmutableMap.of( - "orientation", orientation.value().toUpperCase())); + @Override public void rotate(ScreenOrientation orientation) { + execute(DriverCommand.SET_SCREEN_ORIENTATION, + ImmutableMap.of("orientation", orientation.value().toUpperCase())); } - @Override - public ScreenOrientation getOrientation() { + @Override public ScreenOrientation getOrientation() { Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION); String orientation = response.getValue().toString().toLowerCase(); if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) { @@ -598,18 +580,15 @@ public ScreenOrientation getOrientation() { } else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) { return ScreenOrientation.PORTRAIT; } else { - throw new WebDriverException("Unexpected orientation returned: " - + orientation); + throw new WebDriverException("Unexpected orientation returned: " + orientation); } } - @Override - public Location location() { + @Override public Location location() { return locationContext.location(); } - @Override - public void setLocation(Location location) { + @Override public void setLocation(Location location) { locationContext.setLocation(location); } @@ -617,8 +596,7 @@ public void setLocation(Location location) { /** * This method is deprecated. It is going to be removed in the next release. * Be careful. - */ - public String getAppStrings() { + */ public String getAppStrings() { Response response = execute(GET_STRINGS); return response.getValue().toString(); } @@ -627,53 +605,40 @@ public String getAppStrings() { /** * This method is deprecated. It is going to be removed in the next release. * Be careful. - */ - public String getAppStrings(String language) { - Response response = execute(GET_STRINGS, - getCommandImmutableMap(LANGUAGE_PARAM, language)); + */ public String getAppStrings(String language) { + Response response = execute(GET_STRINGS, getCommandImmutableMap(LANGUAGE_PARAM, language)); return response.getValue().toString(); } /** * @return a map with localized strings defined in the app - * * @see HasAppStrings#getAppStringMap() */ - @Override - public Map getAppStringMap() { + @Override public Map getAppStringMap() { Response response = execute(GET_STRINGS); return (Map) response.getValue(); } /** - * @param language - * strings language code + * @param language strings language code * @return a map with localized strings defined in the app - * * @see HasAppStrings#getAppStringMap(String) */ - @Override - public Map getAppStringMap(String language) { - Response response = execute(GET_STRINGS, - getCommandImmutableMap(LANGUAGE_PARAM, language)); + @Override public Map getAppStringMap(String language) { + Response response = execute(GET_STRINGS, getCommandImmutableMap(LANGUAGE_PARAM, language)); return (Map) response.getValue(); } /** - * @param language - * strings language code - * @param stringFile - * strings filename + * @param language strings language code + * @param stringFile strings filename * @return a map with localized strings defined in the app - * * @see HasAppStrings#getAppStringMap(String, String) */ - @Override - public Map getAppStringMap(String language, String stringFile) { - String[] parameters = new String[] { LANGUAGE_PARAM, STRING_FILE_PARAM }; - Object[] values = new Object[] { language, stringFile }; - Response response = execute(GET_STRINGS, - getCommandImmutableMap(parameters, values)); + @Override public Map getAppStringMap(String language, String stringFile) { + String[] parameters = new String[] {LANGUAGE_PARAM, STRING_FILE_PARAM}; + Object[] values = new Object[] {language, stringFile}; + Response response = execute(GET_STRINGS, getCommandImmutableMap(parameters, values)); return (Map) response.getValue(); } @@ -687,34 +652,11 @@ private TouchAction createTap(int x, int y, int duration) { return tap.press(x, y).waitAction(duration).release(); } - @SuppressWarnings("unused") - private static CommandInfo deleteC(String url) { - return new CommandInfo(url, HttpMethod.DELETE); - } - public URL getRemoteAddress() { return remoteAddress; } - /** - * Checks if a string is null, empty, or whitespace. - * - * @param str - * String to check. - * - * @return True if str is not null or empty. - */ - protected static boolean _isNotNullOrEmpty(String str) { - return str != null && !str.isEmpty() && str.trim().length() > 0; - } - - protected static boolean _isNotNullOrEmpty(Object ob) { - return ob != null; - } - - @Override - public abstract RequiredElementType scrollTo(String text); + @Override public abstract RequiredElementType scrollTo(String text); - @Override - public abstract RequiredElementType scrollToExact(String text); -} \ No newline at end of file + @Override public abstract RequiredElementType scrollToExact(String text); +} diff --git a/src/main/java/io/appium/java_client/AppiumExecutionMethod.java b/src/main/java/io/appium/java_client/AppiumExecutionMethod.java index c338761df..83570e025 100644 --- a/src/main/java/io/appium/java_client/AppiumExecutionMethod.java +++ b/src/main/java/io/appium/java_client/AppiumExecutionMethod.java @@ -23,21 +23,21 @@ import java.util.Map; public class AppiumExecutionMethod implements ExecuteMethod { - private final AppiumDriver driver; + private final AppiumDriver driver; - public AppiumExecutionMethod(AppiumDriver driver) { - this.driver = driver; - } + public AppiumExecutionMethod(AppiumDriver driver) { + this.driver = driver; + } - public Object execute(String commandName, Map parameters) { - Response response; + public Object execute(String commandName, Map parameters) { + Response response; - if (parameters == null || parameters.isEmpty()) { - response = driver.execute(commandName, ImmutableMap.of()); - } else { - response = driver.execute(commandName, parameters); - } + if (parameters == null || parameters.isEmpty()) { + response = driver.execute(commandName, ImmutableMap.of()); + } else { + response = driver.execute(commandName, parameters); + } - return response.getValue(); - } + return response.getValue(); + } } diff --git a/src/main/java/io/appium/java_client/AppiumSetting.java b/src/main/java/io/appium/java_client/AppiumSetting.java index 11b436b50..697e1457f 100644 --- a/src/main/java/io/appium/java_client/AppiumSetting.java +++ b/src/main/java/io/appium/java_client/AppiumSetting.java @@ -18,19 +18,18 @@ /** * Enums defining constants for Appium Settings which can be set and toggled during a test session. - * */ public enum AppiumSetting { - IGNORE_UNIMPORTANT_VIEWS("ignoreUnimportantViews"); - private String name; + IGNORE_UNIMPORTANT_VIEWS("ignoreUnimportantViews"); + private String name; - private AppiumSetting(String name) { - this.name = name; - } + private AppiumSetting(String name) { + this.name = name; + } - public String toString() { - return this.name; - } + public String toString() { + return this.name; + } } diff --git a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java index d8d368612..83babee50 100644 --- a/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java +++ b/src/main/java/io/appium/java_client/DefaultGenericMobileDriver.java @@ -16,10 +16,11 @@ package io.appium.java_client; -import io.appium.java_client.MobileDriver; import io.appium.java_client.generic.searchcontext.*; - -import org.openqa.selenium.*; +import org.openqa.selenium.By; +import org.openqa.selenium.Capabilities; +import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Mouse; import org.openqa.selenium.remote.CommandExecutor; import org.openqa.selenium.remote.RemoteWebDriver; @@ -28,51 +29,47 @@ import java.util.List; import java.util.Map; -@SuppressWarnings({ "unchecked", "rawtypes" }) -abstract class DefaultGenericMobileDriver extends RemoteWebDriver implements MobileDriver, - GenericSearchContext, GenericFindsById, GenericFindsByXPath, GenericFindsByLinkText, GenericFindsByTagName, - GenericFindsByClassName, GenericFindsByCssSelector, GenericFindsByName{ +@SuppressWarnings({"unchecked", "rawtypes"}) +abstract class DefaultGenericMobileDriver extends RemoteWebDriver + implements MobileDriver, GenericSearchContext, GenericFindsById, GenericFindsByXPath, + GenericFindsByLinkText, GenericFindsByTagName, GenericFindsByClassName, + GenericFindsByCssSelector, GenericFindsByName { - public DefaultGenericMobileDriver(CommandExecutor executor, Capabilities desiredCapabilities){ - super(executor, desiredCapabilities); + public DefaultGenericMobileDriver(CommandExecutor executor, Capabilities desiredCapabilities) { + super(executor, desiredCapabilities); } - @Override - public Response execute(String driverCommand, Map parameters) { + @Override public Response execute(String driverCommand, Map parameters) { return super.execute(driverCommand, parameters); } - @Override - public List findElements(By by){ + @Override public List findElements(By by) { return super.findElements(by); } - @Override - public T findElement(By by){ + @Override public T findElement(By by) { return (T) super.findElement(by); } - @Override - public List findElementsById(String id){ + @Override public List findElementsById(String id) { return super.findElementsById(id); } - @Override - public T findElementById(String id){ + @Override public T findElementById(String id) { return (T) super.findElementById(id); } /** * @throws WebDriverException his method doesn't work against native app UI. */ - public T findElementByLinkText(String using) throws WebDriverException{ + public T findElementByLinkText(String using) throws WebDriverException { return (T) super.findElementByLinkText(using); } /** * @throws WebDriverException This method doesn't work against native app UI. */ - public List findElementsByLinkText(String using) throws WebDriverException{ + public List findElementsByLinkText(String using) throws WebDriverException { return super.findElementsByLinkText(using); } @@ -117,14 +114,14 @@ public List findElementsByClassName(String using) { /** * @throws WebDriverException his method doesn't work against native app UI. */ - public T findElementByCssSelector(String using) throws WebDriverException{ + public T findElementByCssSelector(String using) throws WebDriverException { return (T) super.findElementByCssSelector(using); } /** * @throws WebDriverException This method doesn't work against native app UI. */ - public List findElementsByCssSelector(String using) throws WebDriverException{ + public List findElementsByCssSelector(String using) throws WebDriverException { return super.findElementsByCssSelector(using); } @@ -139,24 +136,21 @@ public List findElementsByXPath(String using) { @Override /** * @throws WebDriverException This method is not applicable with browser/webview UI. - */ - public T findElementByAccessibilityId(String using) throws WebDriverException { + */ public T findElementByAccessibilityId(String using) throws WebDriverException { return (T) findElement("accessibility id", using); } @Override /** * @throws WebDriverException This method is not applicable with browser/webview UI. - */ - public List findElementsByAccessibilityId(String using) throws WebDriverException{ + */ public List findElementsByAccessibilityId(String using) throws WebDriverException { return (List) findElements("accessibility id", using); } /** * Mouse doesn't work on mobile devices and emulators */ - @Deprecated - public Mouse getMouse(){ + @Deprecated public Mouse getMouse() { return super.getMouse(); } } diff --git a/src/main/java/io/appium/java_client/DefaultGenericMobileElement.java b/src/main/java/io/appium/java_client/DefaultGenericMobileElement.java index 6681e04c4..d47159ff3 100644 --- a/src/main/java/io/appium/java_client/DefaultGenericMobileElement.java +++ b/src/main/java/io/appium/java_client/DefaultGenericMobileElement.java @@ -16,51 +16,40 @@ package io.appium.java_client; -import io.appium.java_client.generic.searchcontext.GenericFindsByClassName; -import io.appium.java_client.generic.searchcontext.GenericFindsByCssSelector; -import io.appium.java_client.generic.searchcontext.GenericFindsById; -import io.appium.java_client.generic.searchcontext.GenericFindsByLinkText; -import io.appium.java_client.generic.searchcontext.GenericFindsByName; -import io.appium.java_client.generic.searchcontext.GenericFindsByTagName; -import io.appium.java_client.generic.searchcontext.GenericFindsByXPath; -import io.appium.java_client.generic.searchcontext.GenericSearchContext; - -import java.util.List; -import java.util.Map; - +import io.appium.java_client.generic.searchcontext.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.remote.Response; -@SuppressWarnings({ "unchecked", "rawtypes" }) -abstract class DefaultGenericMobileElement extends RemoteWebElement implements - GenericSearchContext, GenericFindsById, GenericFindsByXPath, GenericFindsByLinkText, GenericFindsByTagName, - GenericFindsByClassName, GenericFindsByCssSelector, GenericFindsByName, FindsByAccessibilityId, TouchableElement{ +import java.util.List; +import java.util.Map; + +@SuppressWarnings({"unchecked", "rawtypes"}) +abstract class DefaultGenericMobileElement extends RemoteWebElement + implements GenericSearchContext, GenericFindsById, GenericFindsByXPath, + GenericFindsByLinkText, GenericFindsByTagName, GenericFindsByClassName, + GenericFindsByCssSelector, GenericFindsByName, FindsByAccessibilityId, + TouchableElement { - @Override - public Response execute(String driverCommand, Map parameters) { + @Override public Response execute(String driverCommand, Map parameters) { return super.execute(driverCommand, parameters); } - @Override - public List findElements(By by){ + @Override public List findElements(By by) { return super.findElements(by); } - @Override - public T findElement(By by){ + @Override public T findElement(By by) { return (T) super.findElement(by); } - @Override - public List findElementsById(String id){ + @Override public List findElementsById(String id) { return super.findElementsById(id); } - @Override - public T findElementById(String id){ + @Override public T findElementById(String id) { return (T) super.findElementById(id); } @@ -74,7 +63,7 @@ public T findElementByLinkText(String using) throws WebDriverException { /** * @throws WebDriverException This method doesn't work against native app UI. */ - public List findElementsByLinkText(String using) throws WebDriverException{ + public List findElementsByLinkText(String using) throws WebDriverException { return super.findElementsByLinkText(using); } @@ -119,14 +108,14 @@ public List findElementsByClassName(String using) { /** * @throws WebDriverException his method doesn't work against native app UI. */ - public T findElementByCssSelector(String using) throws WebDriverException{ + public T findElementByCssSelector(String using) throws WebDriverException { return (T) super.findElementByCssSelector(using); } /** * @throws WebDriverException This method doesn't work against native app UI. */ - public List findElementsByCssSelector(String using) throws WebDriverException{ + public List findElementsByCssSelector(String using) throws WebDriverException { return super.findElementsByCssSelector(using); } @@ -138,27 +127,25 @@ public List findElementsByXPath(String using) { return super.findElementsByXPath(using); } - @Override - public T findElementByAccessibilityId(String using) { + @Override public T findElementByAccessibilityId(String using) { return (T) findElement("accessibility id", using); } - @Override - public List findElementsByAccessibilityId(String using) { + @Override public List findElementsByAccessibilityId(String using) { return (List) findElements("accessibility id", using); } /** * @throws WebDriverException because it may not work against native app UI. */ - public void submit() throws WebDriverException{ + public void submit() throws WebDriverException { super.submit(); } /** * @throws WebDriverException because it may not work against native app UI. */ - public String getCssValue(String propertyName) throws WebDriverException{ + public String getCssValue(String propertyName) throws WebDriverException { return super.getCssValue(propertyName); } } diff --git a/src/main/java/io/appium/java_client/DeviceActionShortcuts.java b/src/main/java/io/appium/java_client/DeviceActionShortcuts.java index 9fd7154f1..208f37509 100644 --- a/src/main/java/io/appium/java_client/DeviceActionShortcuts.java +++ b/src/main/java/io/appium/java_client/DeviceActionShortcuts.java @@ -20,11 +20,11 @@ public interface DeviceActionShortcuts { /** - * Hides the keyboard if it is showing. - * On iOS, there are multiple strategies for hiding the keyboard. Defaults to the "tapOutside" strategy (taps outside the keyboard). - * Switch to using hideKeyboard(HideKeyboardStrategy.PRESS_KEY, "Done") if this doesn't work. - */ - void hideKeyboard(); + * Hides the keyboard if it is showing. + * On iOS, there are multiple strategies for hiding the keyboard. Defaults to the "tapOutside" strategy (taps outside the keyboard). + * Switch to using hideKeyboard(HideKeyboardStrategy.PRESS_KEY, "Done") if this doesn't work. + */ + void hideKeyboard(); /* Gets device date and time for both iOS(Supports only real device) and Android devices diff --git a/src/main/java/io/appium/java_client/DriverMobileCommand.java b/src/main/java/io/appium/java_client/DriverMobileCommand.java index ad59b9ffd..9d991d3cb 100644 --- a/src/main/java/io/appium/java_client/DriverMobileCommand.java +++ b/src/main/java/io/appium/java_client/DriverMobileCommand.java @@ -23,5 +23,5 @@ * @author jonahss@gmail.com (Jonah Stiennon) */ public interface DriverMobileCommand { - //TODO Jonah: we'll probably need this + //TODO Jonah: we'll probably need this } diff --git a/src/main/java/io/appium/java_client/ErrorCodesMobile.java b/src/main/java/io/appium/java_client/ErrorCodesMobile.java index 175b630c3..67aae5434 100644 --- a/src/main/java/io/appium/java_client/ErrorCodesMobile.java +++ b/src/main/java/io/appium/java_client/ErrorCodesMobile.java @@ -30,56 +30,55 @@ */ public class ErrorCodesMobile extends ErrorCodes { - public static final int NO_SUCH_CONTEXT = 35; + public static final int NO_SUCH_CONTEXT = 35; - private static Map statusToState = ImmutableMap.builder() - .put(NO_SUCH_CONTEXT, "No such context found") - .build(); + private static Map statusToState = + ImmutableMap.builder().put(NO_SUCH_CONTEXT, "No such context found") + .build(); - /** - * Returns the exception type that corresponds to the given {@code statusCode}. All unrecognized - * status codes will be mapped to {@link WebDriverException WebDriverException.class}. - * - * @param statusCode The status code to convert. - * @return The exception type that corresponds to the provided status code or {@code null} if - * {@code statusCode == 0}. - */ - public Class getExceptionType(int statusCode) { - switch (statusCode) { - case NO_SUCH_CONTEXT: - return NoSuchContextException.class; - default: - return super.getExceptionType(statusCode); + /** + * Returns the exception type that corresponds to the given {@code statusCode}. All unrecognized + * status codes will be mapped to {@link WebDriverException WebDriverException.class}. + * + * @param statusCode The status code to convert. + * @return The exception type that corresponds to the provided status code or {@code null} if + * {@code statusCode == 0}. + */ + public Class getExceptionType(int statusCode) { + switch (statusCode) { + case NO_SUCH_CONTEXT: + return NoSuchContextException.class; + default: + return super.getExceptionType(statusCode); + } } - } - /** - * - * @param message An error message returned by Appium server - * @return The exception type that corresponds to the provided error message or {@code null} if - * there are no matching mobile exceptions. - */ - public Class getExceptionType(String message) { - for (Map.Entry entry: statusToState.entrySet()) { - if (message.contains(entry.getValue())) { - return getExceptionType(entry.getKey()); - } + /** + * @param message An error message returned by Appium server + * @return The exception type that corresponds to the provided error message or {@code null} if + * there are no matching mobile exceptions. + */ + public Class getExceptionType(String message) { + for (Map.Entry entry : statusToState.entrySet()) { + if (message.contains(entry.getValue())) { + return getExceptionType(entry.getKey()); + } + } + return null; } - return null; - } - /** - * Converts a thrown error into the corresponding status code. - * - * @param thrown The thrown error. - * @return The corresponding status code for the given thrown error. - */ - public int toStatusCode(Throwable thrown) { - if (thrown instanceof NoSuchContextException) { - return NO_SUCH_CONTEXT; - } else { - return super.toStatusCode(thrown); + /** + * Converts a thrown error into the corresponding status code. + * + * @param thrown The thrown error. + * @return The corresponding status code for the given thrown error. + */ + public int toStatusCode(Throwable thrown) { + if (thrown instanceof NoSuchContextException) { + return NO_SUCH_CONTEXT; + } else { + return super.toStatusCode(thrown); + } } - } -} \ No newline at end of file +} diff --git a/src/main/java/io/appium/java_client/FindsByAccessibilityId.java b/src/main/java/io/appium/java_client/FindsByAccessibilityId.java index 8fe5cefe9..4ede49e6e 100644 --- a/src/main/java/io/appium/java_client/FindsByAccessibilityId.java +++ b/src/main/java/io/appium/java_client/FindsByAccessibilityId.java @@ -21,7 +21,7 @@ import java.util.List; public interface FindsByAccessibilityId { - T findElementByAccessibilityId(String using); + T findElementByAccessibilityId(String using); - List findElementsByAccessibilityId(String using); -} \ No newline at end of file + List findElementsByAccessibilityId(String using); +} diff --git a/src/main/java/io/appium/java_client/HasAppStrings.java b/src/main/java/io/appium/java_client/HasAppStrings.java index 25a080445..21e5c0161 100644 --- a/src/main/java/io/appium/java_client/HasAppStrings.java +++ b/src/main/java/io/appium/java_client/HasAppStrings.java @@ -24,8 +24,7 @@ public interface HasAppStrings { /** * This method is deprecated. It is going to be removed in the next release. * Be careful. - */ - public String getAppStrings(); + */ public String getAppStrings(); @Deprecated /** @@ -44,8 +43,7 @@ public interface HasAppStrings { /** * Get all defined Strings from an app for the specified language * - * @param language - * strings language code + * @param language strings language code * @return a map with localized strings defined in the app */ Map getAppStringMap(String language); @@ -54,10 +52,8 @@ public interface HasAppStrings { * Get all defined Strings from an app for the specified language and * strings filename * - * @param language - * strings language code - * @param stringFile - * strings filename + * @param language strings language code + * @param stringFile strings filename * @return a map with localized strings defined in the app */ Map getAppStringMap(String language, String stringFile); diff --git a/src/main/java/io/appium/java_client/InteractsWithApps.java b/src/main/java/io/appium/java_client/InteractsWithApps.java index 43c950d05..266ca0782 100644 --- a/src/main/java/io/appium/java_client/InteractsWithApps.java +++ b/src/main/java/io/appium/java_client/InteractsWithApps.java @@ -25,16 +25,14 @@ public interface InteractsWithApps { /** * Install an app on the mobile device * - * @param appPath - * path to app to install + * @param appPath path to app to install */ void installApp(String appPath); /** * Checks if an app is installed on the device * - * @param bundleId - * bundleId of the app + * @param bundleId bundleId of the app * @return True if app is installed, false otherwise */ boolean isAppInstalled(String bundleId); @@ -49,16 +47,14 @@ public interface InteractsWithApps { * requested. This is a synchronous method, it returns after the back has * been returned to the foreground. * - * @param seconds - * Number of seconds to run App in background + * @param seconds Number of seconds to run App in background */ void runAppInBackground(int seconds); /** * Remove the specified app from the device (uninstall) * - * @param bundleId - * the bunble identifier (or app id) of the app to remove + * @param bundleId the bunble identifier (or app id) of the app to remove */ void removeApp(String bundleId); diff --git a/src/main/java/io/appium/java_client/InteractsWithFiles.java b/src/main/java/io/appium/java_client/InteractsWithFiles.java index 43264aee6..21d83f4c3 100644 --- a/src/main/java/io/appium/java_client/InteractsWithFiles.java +++ b/src/main/java/io/appium/java_client/InteractsWithFiles.java @@ -19,12 +19,10 @@ public interface InteractsWithFiles { /** - * - * @param remotePath - * On Android and iOS, this is either the path to the file - * (relative to the root of the app's file system). On iOS only, - * if path starts with /AppName.app, which will be replaced with - * the application's .app directory + * @param remotePath On Android and iOS, this is either the path to the file + * (relative to the root of the app's file system). On iOS only, + * if path starts with /AppName.app, which will be replaced with + * the application's .app directory * @return A byte array of Base64 encoded data. */ byte[] pullFile(String remotePath); @@ -33,13 +31,12 @@ public interface InteractsWithFiles { * Pull a folder from the simulator/device. Does not work on iOS Real * Devices, but works on simulators * - * @param remotePath - * On Android and iOS, this is either the path to the file - * (relative to the root of the app's file system). On iOS only, - * if path starts with /AppName.app, which will be replaced with - * the application's .app directory + * @param remotePath On Android and iOS, this is either the path to the file + * (relative to the root of the app's file system). On iOS only, + * if path starts with /AppName.app, which will be replaced with + * the application's .app directory * @return A byte array of Base64 encoded data, representing a ZIP ARCHIVE - * of the contents of the requested folder. + * of the contents of the requested folder. */ byte[] pullFolder(String remotePath); diff --git a/src/main/java/io/appium/java_client/MissingParameterException.java b/src/main/java/io/appium/java_client/MissingParameterException.java index 10e35f78d..4404d9b46 100644 --- a/src/main/java/io/appium/java_client/MissingParameterException.java +++ b/src/main/java/io/appium/java_client/MissingParameterException.java @@ -16,15 +16,15 @@ package io.appium.java_client; -@SuppressWarnings("serial") -public class MissingParameterException extends IllegalArgumentException { +@SuppressWarnings("serial") public class MissingParameterException + extends IllegalArgumentException { - public MissingParameterException(String reason) { - super(reason); - } + public MissingParameterException(String reason) { + super(reason); + } - public MissingParameterException(String reason, Throwable cause) { - super(reason, cause); - } + public MissingParameterException(String reason, Throwable cause) { + super(reason, cause); + } -} \ No newline at end of file +} diff --git a/src/main/java/io/appium/java_client/MobileBy.java b/src/main/java/io/appium/java_client/MobileBy.java index 8a88ae95b..cf2ffce96 100644 --- a/src/main/java/io/appium/java_client/MobileBy.java +++ b/src/main/java/io/appium/java_client/MobileBy.java @@ -26,109 +26,104 @@ /** * Created by jonahss on 4/10/14. */ -@SuppressWarnings("serial") -public abstract class MobileBy extends By { +@SuppressWarnings("serial") public abstract class MobileBy extends By { - public static By IosUIAutomation(final String uiautomationText) { - if (uiautomationText == null) { - throw new IllegalArgumentException("Must supply an iOS UIAutomation string"); + public static By IosUIAutomation(final String uiautomationText) { + if (uiautomationText == null) { + throw new IllegalArgumentException("Must supply an iOS UIAutomation string"); + } + + return new ByIosUIAutomation(uiautomationText); } - return new ByIosUIAutomation(uiautomationText); - } + public static By AndroidUIAutomator(final String uiautomatorText) { + if (uiautomatorText == null) { + throw new IllegalArgumentException("Must supply an Android UIAutomator string"); + } - public static By AndroidUIAutomator(final String uiautomatorText) { - if (uiautomatorText == null) { - throw new IllegalArgumentException("Must supply an Android UIAutomator string"); + return new ByAndroidUIAutomator(uiautomatorText); } - return new ByAndroidUIAutomator(uiautomatorText); - } + public static By AccessibilityId(final String id) { + if (id == null) { + throw new IllegalArgumentException("Must supply a uiautomationText"); + } - public static By AccessibilityId(final String id) { - if (id == null) { - throw new IllegalArgumentException("Must supply a uiautomationText"); + return new ByAccessibilityId(id); } - return new ByAccessibilityId(id); - } + public static class ByIosUIAutomation extends By implements Serializable { - public static class ByIosUIAutomation extends By implements Serializable { + private final String automationText; - private final String automationText; + public ByIosUIAutomation(String uiautomationText) { + automationText = uiautomationText; + } - public ByIosUIAutomation(String uiautomationText) { - automationText = uiautomationText; - } + @SuppressWarnings("unchecked") @Override + public List findElements(SearchContext context) { + return (List) ((FindsByIosUIAutomation) context). + findElementsByIosUIAutomation(automationText); + } - @SuppressWarnings("unchecked") - @Override - public List findElements(SearchContext context) { - return (List) ((FindsByIosUIAutomation) context). - findElementsByIosUIAutomation(automationText); - } + @Override public WebElement findElement(SearchContext context) { + return ((FindsByIosUIAutomation) context) + .findElementByIosUIAutomation(automationText); + } - @Override - public WebElement findElement(SearchContext context) { - return ((FindsByIosUIAutomation) context).findElementByIosUIAutomation(automationText); + @Override public String toString() { + return "By.IosUIAutomation: " + automationText; + } } - @Override - public String toString() { - return "By.IosUIAutomation: " + automationText; - } - } - public static class ByAndroidUIAutomator extends By implements Serializable { + public static class ByAndroidUIAutomator extends By implements Serializable { - private final String automatorText; + private final String automatorText; - public ByAndroidUIAutomator(String uiautomatorText) { - automatorText = uiautomatorText; - } + public ByAndroidUIAutomator(String uiautomatorText) { + automatorText = uiautomatorText; + } - @SuppressWarnings("unchecked") - @Override - public List findElements(SearchContext context) { - return (List) ((FindsByAndroidUIAutomator) context). - findElementsByAndroidUIAutomator(automatorText); - } + @SuppressWarnings("unchecked") @Override + public List findElements(SearchContext context) { + return (List) ((FindsByAndroidUIAutomator) context). + findElementsByAndroidUIAutomator(automatorText); + } + + @Override public WebElement findElement(SearchContext context) { + return ((FindsByAndroidUIAutomator) context) + .findElementByAndroidUIAutomator(automatorText); + } - @Override - public WebElement findElement(SearchContext context) { - return ((FindsByAndroidUIAutomator) context).findElementByAndroidUIAutomator(automatorText); + @Override public String toString() { + return "By.AndroidUIAutomator: " + automatorText; + } } - @Override - public String toString() { return "By.AndroidUIAutomator: " + automatorText; } - } - -public static class ByAccessibilityId extends By implements Serializable { + public static class ByAccessibilityId extends By implements Serializable { - private final String id; + private final String id; - public ByAccessibilityId(String id) { - this.id = id; - } + public ByAccessibilityId(String id) { + this.id = id; + } - @SuppressWarnings("unchecked") - @Override - public List findElements(SearchContext context) { - return (List) - ((FindsByAccessibilityId) context).findElementsByAccessibilityId(id); - } + @SuppressWarnings("unchecked") @Override + public List findElements(SearchContext context) { + return (List) ((FindsByAccessibilityId) context) + .findElementsByAccessibilityId(id); + } - @Override - public WebElement findElement(SearchContext context) { - return ((FindsByAccessibilityId) context).findElementByAccessibilityId(id); - } + @Override public WebElement findElement(SearchContext context) { + return ((FindsByAccessibilityId) context).findElementByAccessibilityId(id); + } - @Override - public String toString() { - return "By.AccessibilityId: " + id; + @Override public String toString() { + return "By.AccessibilityId: " + id; + } } - } } diff --git a/src/main/java/io/appium/java_client/MobileCommand.java b/src/main/java/io/appium/java_client/MobileCommand.java index 66584429d..0ad48e553 100644 --- a/src/main/java/io/appium/java_client/MobileCommand.java +++ b/src/main/java/io/appium/java_client/MobileCommand.java @@ -25,118 +25,93 @@ /** * The repository of mobile commands defined in the Mobile JSON * wire protocol. - * */ public class MobileCommand { - public final static String RESET = "reset"; - public final static String GET_STRINGS = "getStrings"; - public final static String PRESS_KEY_CODE = "pressKeyCode"; - public final static String LONG_PRESS_KEY_CODE = "longPressKeyCode"; - public final static String CURRENT_ACTIVITY = "currentActivity"; - public final static String SET_VALUE = "setValue"; - public final static String REPLACE_VALUE = "replaceValue"; - public final static String PULL_FILE = "pullFile"; - public final static String PUSH_FILE = "pushFile"; - public final static String PULL_FOLDER = "pullFolder"; - public final static String HIDE_KEYBOARD = "hideKeyboard"; - public final static String RUN_APP_IN_BACKGROUND = "runAppInBackground"; - public final static String PERFORM_TOUCH_ACTION = "performTouchAction"; - public final static String PERFORM_MULTI_TOUCH = "performMultiTouch"; - public final static String IS_APP_INSTALLED = "isAppInstalled"; - public final static String INSTALL_APP = "installApp"; - public final static String REMOVE_APP = "removeApp"; - public final static String LAUNCH_APP = "launchApp"; - public final static String CLOSE_APP = "closeApp"; - public final static String END_TEST_COVERAGE = "endTestCoverage"; - public final static String LOCK = "lock"; - public final static String IS_LOCKED = "isLocked"; - public final static String SHAKE = "shake"; - public final static String COMPLEX_FIND = "complexFind"; - public final static String OPEN_NOTIFICATIONS = "openNotifications"; - public final static String GET_NETWORK_CONNECTION = "getNetworkConnection"; - public final static String SET_NETWORK_CONNECTION = "setNetworkConnection"; - public final static String GET_SETTINGS = "getSettings"; - public final static String SET_SETTINGS = "setSettings"; - public final static String START_ACTIVITY = "startActivity"; - public final static String TOGGLE_LOCATION_SERVICES = "toggleLocationServices"; - public final static String GET_DEVICE_TIME = "getDeviceTime"; - public final static String UNLOCK = "unlock"; + public final static String RESET = "reset"; + public final static String GET_STRINGS = "getStrings"; + public final static String PRESS_KEY_CODE = "pressKeyCode"; + public final static String LONG_PRESS_KEY_CODE = "longPressKeyCode"; + public final static String CURRENT_ACTIVITY = "currentActivity"; + public final static String SET_VALUE = "setValue"; + public final static String REPLACE_VALUE = "replaceValue"; + public final static String PULL_FILE = "pullFile"; + public final static String PUSH_FILE = "pushFile"; + public final static String PULL_FOLDER = "pullFolder"; + public final static String HIDE_KEYBOARD = "hideKeyboard"; + public final static String RUN_APP_IN_BACKGROUND = "runAppInBackground"; + public final static String PERFORM_TOUCH_ACTION = "performTouchAction"; + public final static String PERFORM_MULTI_TOUCH = "performMultiTouch"; + public final static String IS_APP_INSTALLED = "isAppInstalled"; + public final static String INSTALL_APP = "installApp"; + public final static String REMOVE_APP = "removeApp"; + public final static String LAUNCH_APP = "launchApp"; + public final static String CLOSE_APP = "closeApp"; + public final static String END_TEST_COVERAGE = "endTestCoverage"; + public final static String LOCK = "lock"; + public final static String IS_LOCKED = "isLocked"; + public final static String SHAKE = "shake"; + public final static String COMPLEX_FIND = "complexFind"; + public final static String OPEN_NOTIFICATIONS = "openNotifications"; + public final static String GET_NETWORK_CONNECTION = "getNetworkConnection"; + public final static String SET_NETWORK_CONNECTION = "setNetworkConnection"; + public final static String GET_SETTINGS = "getSettings"; + public final static String SET_SETTINGS = "setSettings"; + public final static String START_ACTIVITY = "startActivity"; + public final static String TOGGLE_LOCATION_SERVICES = "toggleLocationServices"; + public final static String GET_DEVICE_TIME = "getDeviceTime"; + public final static String UNLOCK = "unlock"; + static final Map commandRepository = getMobileCommands(); - static CommandInfo getC(String url) { - return new CommandInfo(url, HttpMethod.GET); - } - - static CommandInfo postC(String url) { - return new CommandInfo(url, HttpMethod.POST); - } - - static final Map commandRepository = getMobileCommands(); + static CommandInfo getC(String url) { + return new CommandInfo(url, HttpMethod.GET); + } - private static Map getMobileCommands(){ - if (commandRepository != null) { - return commandRepository; + static CommandInfo postC(String url) { + return new CommandInfo(url, HttpMethod.POST); } - ImmutableMap.Builder builder = ImmutableMap - .builder(); - builder.put(RESET, postC("/session/:sessionId/appium/app/reset")) - .put(GET_STRINGS, - postC("/session/:sessionId/appium/app/strings")) - .put(PRESS_KEY_CODE, - postC("/session/:sessionId/appium/device/press_keycode")) - .put(LONG_PRESS_KEY_CODE, - postC("/session/:sessionId/appium/device/long_press_keycode")) - .put(CURRENT_ACTIVITY, - getC("/session/:sessionId/appium/device/current_activity")) - .put(SET_VALUE, - postC("/session/:sessionId/appium/element/:id/value")) - .put(REPLACE_VALUE, - postC("/session/:sessionId/appium/element/:id/replace_value")) - .put(PULL_FILE, - postC("/session/:sessionId/appium/device/pull_file")) - .put(PULL_FOLDER, - postC("/session/:sessionId/appium/device/pull_folder")) - .put(HIDE_KEYBOARD, - postC("/session/:sessionId/appium/device/hide_keyboard")) - .put(PUSH_FILE, - postC("/session/:sessionId/appium/device/push_file")) - .put(RUN_APP_IN_BACKGROUND, - postC("/session/:sessionId/appium/app/background")) - .put(PERFORM_TOUCH_ACTION, - postC("/session/:sessionId/touch/perform")) - .put(PERFORM_MULTI_TOUCH, - postC("/session/:sessionId/touch/multi/perform")) - .put(IS_APP_INSTALLED, - postC("/session/:sessionId/appium/device/app_installed")) - .put(INSTALL_APP, - postC("/session/:sessionId/appium/device/install_app")) - .put(REMOVE_APP, - postC("/session/:sessionId/appium/device/remove_app")) + private static Map getMobileCommands() { + if (commandRepository != null) { + return commandRepository; + } + + ImmutableMap.Builder builder = ImmutableMap.builder(); + builder.put(RESET, postC("/session/:sessionId/appium/app/reset")) + .put(GET_STRINGS, postC("/session/:sessionId/appium/app/strings")) + .put(PRESS_KEY_CODE, postC("/session/:sessionId/appium/device/press_keycode")) + .put(LONG_PRESS_KEY_CODE, postC("/session/:sessionId/appium/device/long_press_keycode")) + .put(CURRENT_ACTIVITY, getC("/session/:sessionId/appium/device/current_activity")) + .put(SET_VALUE, postC("/session/:sessionId/appium/element/:id/value")) + .put(REPLACE_VALUE, postC("/session/:sessionId/appium/element/:id/replace_value")) + .put(PULL_FILE, postC("/session/:sessionId/appium/device/pull_file")) + .put(PULL_FOLDER, postC("/session/:sessionId/appium/device/pull_folder")) + .put(HIDE_KEYBOARD, postC("/session/:sessionId/appium/device/hide_keyboard")) + .put(PUSH_FILE, postC("/session/:sessionId/appium/device/push_file")) + .put(RUN_APP_IN_BACKGROUND, postC("/session/:sessionId/appium/app/background")) + .put(PERFORM_TOUCH_ACTION, postC("/session/:sessionId/touch/perform")) + .put(PERFORM_MULTI_TOUCH, postC("/session/:sessionId/touch/multi/perform")) + .put(IS_APP_INSTALLED, postC("/session/:sessionId/appium/device/app_installed")) + .put(INSTALL_APP, postC("/session/:sessionId/appium/device/install_app")) + .put(REMOVE_APP, postC("/session/:sessionId/appium/device/remove_app")) .put(LAUNCH_APP, postC("/session/:sessionId/appium/app/launch")) .put(CLOSE_APP, postC("/session/:sessionId/appium/app/close")) - .put(END_TEST_COVERAGE, - postC("/session/:sessionId/appium/app/end_test_coverage")) + .put(END_TEST_COVERAGE, postC("/session/:sessionId/appium/app/end_test_coverage")) .put(LOCK, postC("/session/:sessionId/appium/device/lock")) - .put(IS_LOCKED, - postC("/session/:sessionId/appium/device/is_locked")) + .put(IS_LOCKED, postC("/session/:sessionId/appium/device/is_locked")) .put(SHAKE, postC("/session/:sessionId/appium/device/shake")) - .put(COMPLEX_FIND, - postC("/session/:sessionId/appium/app/complex_find")) - .put(OPEN_NOTIFICATIONS, - postC("/session/:sessionId/appium/device/open_notifications")) - .put(GET_NETWORK_CONNECTION, - getC("/session/:sessionId/network_connection")) - .put(SET_NETWORK_CONNECTION, - postC("/session/:sessionId/network_connection")) + .put(COMPLEX_FIND, postC("/session/:sessionId/appium/app/complex_find")) + .put(OPEN_NOTIFICATIONS, postC("/session/:sessionId/appium/device/open_notifications")) + .put(GET_NETWORK_CONNECTION, getC("/session/:sessionId/network_connection")) + .put(SET_NETWORK_CONNECTION, postC("/session/:sessionId/network_connection")) .put(GET_SETTINGS, getC("/session/:sessionId/appium/settings")) .put(SET_SETTINGS, postC("/session/:sessionId/appium/settings")) - .put(START_ACTIVITY, - postC("/session/:sessionId/appium/device/start_activity")) - .put(TOGGLE_LOCATION_SERVICES, postC("/session/:sessionId/appium/device/toggle_location_services")) - .put(GET_DEVICE_TIME,getC("/session/:sessionId/appium/device/system_time")) + .put(START_ACTIVITY, postC("/session/:sessionId/appium/device/start_activity")) + .put(TOGGLE_LOCATION_SERVICES, + postC("/session/:sessionId/appium/device/toggle_location_services")) + .put(GET_DEVICE_TIME, getC("/session/:sessionId/appium/device/system_time")) .put(UNLOCK, postC("/session/:sessionId/appium/device/unlock")); - return builder.build(); - } + return builder.build(); + } } diff --git a/src/main/java/io/appium/java_client/MobileDriver.java b/src/main/java/io/appium/java_client/MobileDriver.java index fbb66ccfa..0d26e8839 100644 --- a/src/main/java/io/appium/java_client/MobileDriver.java +++ b/src/main/java/io/appium/java_client/MobileDriver.java @@ -25,10 +25,8 @@ import java.util.Map; -public interface MobileDriver extends WebDriver, - PerformsTouchActions, - ContextAware, Rotatable, FindsByAccessibilityId, LocationContext, - DeviceActionShortcuts, TouchShortcuts, InteractsWithFiles, - InteractsWithApps, ScrollsTo, HasAppStrings { +public interface MobileDriver extends WebDriver, PerformsTouchActions, ContextAware, Rotatable, + FindsByAccessibilityId, LocationContext, DeviceActionShortcuts, TouchShortcuts, + InteractsWithFiles, InteractsWithApps, ScrollsTo, HasAppStrings { Response execute(String driverCommand, Map parameters); } diff --git a/src/main/java/io/appium/java_client/MobileElement.java b/src/main/java/io/appium/java_client/MobileElement.java index f79772a98..a2d08a4c3 100644 --- a/src/main/java/io/appium/java_client/MobileElement.java +++ b/src/main/java/io/appium/java_client/MobileElement.java @@ -25,52 +25,46 @@ import java.util.ArrayList; import java.util.List; -@SuppressWarnings({ "unchecked"}) -public abstract class MobileElement extends DefaultGenericMobileElement { +@SuppressWarnings({"unchecked"}) public abstract class MobileElement + extends DefaultGenericMobileElement { protected FileDetector fileDetector; public Point getCenter() { Point upperLeft = this.getLocation(); Dimension dimensions = this.getSize(); - return new Point(upperLeft.getX() + dimensions.getWidth() / 2, upperLeft.getY() + dimensions.getHeight() / 2); + return new Point(upperLeft.getX() + dimensions.getWidth() / 2, + upperLeft.getY() + dimensions.getHeight() / 2); } - @Override - public void pinch() { + @Override public void pinch() { ((AppiumDriver) parent).pinch(this); } - @Override - public void tap(int fingers, int duration) { + @Override public void tap(int fingers, int duration) { ((AppiumDriver) parent).tap(fingers, this, duration); } - @Override - public void zoom() { + @Override public void zoom() { ((AppiumDriver) parent).zoom(this); } - @Override - public void swipe(SwipeElementDirection direction, int duration) { + @Override public void swipe(SwipeElementDirection direction, int duration) { direction.swipe((AppiumDriver) parent, this, 0, 0, duration); } - @Override - public void swipe(SwipeElementDirection direction, int offsetFromStartBorder, - int offsetFromEndBorder, int duration) throws IllegalCoordinatesException { - direction.swipe((AppiumDriver) parent, this, offsetFromStartBorder, - offsetFromEndBorder, duration); + @Override public void swipe(SwipeElementDirection direction, int offsetFromStartBorder, + int offsetFromEndBorder, int duration) throws IllegalCoordinatesException { + direction.swipe((AppiumDriver) parent, this, offsetFromStartBorder, offsetFromEndBorder, + duration); } - @Override - public List findElements(By by){ + @Override public List findElements(By by) { return super.findElements(by); } - @Override - public List findElementsById(String id){ + @Override public List findElementsById(String id) { return super.findElementsById(id); } @@ -102,11 +96,10 @@ public List findElementsByXPath(String using) { return super.findElementsByXPath(using); } - @Override - public List findElementsByAccessibilityId(String using) { + @Override public List findElementsByAccessibilityId(String using) { List result = new ArrayList(); List found = findElements("accessibility id", using); - for (WebElement e: found) + for (WebElement e : found) result.add((MobileElement) e); return result; } diff --git a/src/main/java/io/appium/java_client/MultiTouchAction.java b/src/main/java/io/appium/java_client/MultiTouchAction.java index 8178d6784..2df0d3a7e 100644 --- a/src/main/java/io/appium/java_client/MultiTouchAction.java +++ b/src/main/java/io/appium/java_client/MultiTouchAction.java @@ -23,68 +23,69 @@ /** * Used for Webdriver 3 multi-touch gestures * See the Webriver 3 spec https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html - * + *

* The MultiTouchAction object is a collection of TouchAction objects - * (remember that TouchAction objects are in turn, a chain of individual actions) - * + * (remember that TouchAction objects are in turn, a chain of individual actions) + *

* Add multiple TouchAction objects using the add() method. * When perform() method is called, all actions are sent to the driver. - * + *

* The driver performs the first step of each TouchAction object simultaneously as a multi-touch "execution group". - * Conceptually, the number of TouchAction objects added to the MultiTouchAction is equal to the number of "fingers" or - * other appendages or tools touching the screen at the same time as part of this multi-gesture. + * Conceptually, the number of TouchAction objects added to the MultiTouchAction is equal to the number of "fingers" or + * other appendages or tools touching the screen at the same time as part of this multi-gesture. * Then the driver performs the second step of each TouchAction object and another "execution group", and the third, and so on. - * + *

* Using a waitAction() action within a TouchAction takes up one of the slots in an "execution group", so these can be used to - * sync up complex actions. - * + * sync up complex actions. + *

* Calling perform() sends the action command to the Mobile Driver. Otherwise, more and more actions can be chained. */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class MultiTouchAction { +@SuppressWarnings({"rawtypes", "unchecked"}) public class MultiTouchAction { - private MobileDriver driver; - ImmutableList.Builder actions; + ImmutableList.Builder actions; + private MobileDriver driver; - public MultiTouchAction(MobileDriver driver) { - this.driver = driver; - actions = ImmutableList.builder(); - } - - /** - * Add a TouchAction to this multi-touch gesture - * @param action TouchAction to add to this gesture - * @return This MultiTouchAction, for chaining - */ - public MultiTouchAction add(TouchAction action) { - actions.add(action); + public MultiTouchAction(MobileDriver driver) { + this.driver = driver; + actions = ImmutableList.builder(); + } - return this; - } + /** + * Add a TouchAction to this multi-touch gesture + * + * @param action TouchAction to add to this gesture + * @return This MultiTouchAction, for chaining + */ + public MultiTouchAction add(TouchAction action) { + actions.add(action); - /** - * Perform the multi-touch action on the mobile driver. - */ - public void perform() { - int size = actions.build().size(); - if (size > 1) { - driver.performMultiTouchAction(this); - } else if (size == 1) { - //android doesn't like having multi-touch actions with only a single TouchAction... - driver.performTouchAction((TouchAction)actions.build().get(0)); - } else { - throw new MissingParameterException("MultiTouch action must have at least one TouchAction added before it can be performed"); + return this; } - } + /** + * Perform the multi-touch action on the mobile driver. + */ + public void perform() { + int size = actions.build().size(); + if (size > 1) { + driver.performMultiTouchAction(this); + } else if (size == 1) { + //android doesn't like having multi-touch actions with only a single TouchAction... + driver.performTouchAction((TouchAction) actions.build().get(0)); + } else { + throw new MissingParameterException( + "MultiTouch action must have at least one TouchAction added before it can be performed"); + } + + } - protected ImmutableMap getParameters() { - ImmutableList.Builder listOfActionChains = ImmutableList.builder(); - ImmutableList touchActions = actions.build(); + protected ImmutableMap getParameters() { + ImmutableList.Builder listOfActionChains = ImmutableList.builder(); + ImmutableList touchActions = actions.build(); - for (TouchAction action : touchActions) { - listOfActionChains.add(action.getParameters().get("actions")); + for (TouchAction action : touchActions) { + listOfActionChains.add(action.getParameters().get("actions")); + } + return ImmutableMap.of("actions", listOfActionChains.build()); } - return ImmutableMap.of("actions", listOfActionChains.build()); - } } diff --git a/src/main/java/io/appium/java_client/NetworkConnectionSetting.java b/src/main/java/io/appium/java_client/NetworkConnectionSetting.java index 5f4c1d0f3..f05afdc67 100644 --- a/src/main/java/io/appium/java_client/NetworkConnectionSetting.java +++ b/src/main/java/io/appium/java_client/NetworkConnectionSetting.java @@ -23,81 +23,87 @@ */ public class NetworkConnectionSetting { - public int value = 0; - private int airplaneMode = 1; - private int wifi = 2; - private int data = 4; - - /** - * - * @param airplaneMode boolean for airplane mode enabled - * @param wifi boolean for wifi enabled - * @param data boolean for data enabled - */ - public NetworkConnectionSetting(boolean airplaneMode, boolean wifi, boolean data) { - int a = airplaneMode ? this.airplaneMode : 0; - int b = wifi ? this.wifi : 0; - int c = data ? this.data : 0; - - value = a | b | c; - } - - /** - * Instantiate Network Connection Settings with the straight-up bitmask. See the Mobile JSON Wire Protocol spec for details. - * @param bitmask a straight-up bitmask - */ - public NetworkConnectionSetting(int bitmask) { - value = bitmask; - } - - public boolean airplaneModeEnabled() { return (value & airplaneMode) != 0; } - - public boolean wifiEnabled() { return (value & wifi) != 0; } - - public boolean dataEnabled() { return (value & data) != 0; } - - public void setAirplaneMode(boolean enable) { - if (enable) { - value = value | airplaneMode; - } else { - value = value & ~airplaneMode; + public int value = 0; + private int airplaneMode = 1; + private int wifi = 2; + private int data = 4; + + /** + * @param airplaneMode boolean for airplane mode enabled + * @param wifi boolean for wifi enabled + * @param data boolean for data enabled + */ + public NetworkConnectionSetting(boolean airplaneMode, boolean wifi, boolean data) { + int a = airplaneMode ? this.airplaneMode : 0; + int b = wifi ? this.wifi : 0; + int c = data ? this.data : 0; + + value = a | b | c; } - } - public void setWifi(boolean enable) { - if (enable) { - value = value | wifi; - } else { - value = value & ~wifi; + /** + * Instantiate Network Connection Settings with the straight-up bitmask. See the Mobile JSON Wire Protocol spec for details. + * + * @param bitmask a straight-up bitmask + */ + public NetworkConnectionSetting(int bitmask) { + value = bitmask; } - } - public void setData(boolean enable) { - if (enable) { - value = value | data; - } else { - value = value & ~data; + public boolean airplaneModeEnabled() { + return (value & airplaneMode) != 0; } - } - public int hashCode() { - return value; - } + public boolean wifiEnabled() { + return (value & wifi) != 0; + } + + public boolean dataEnabled() { + return (value & data) != 0; + } + + public void setAirplaneMode(boolean enable) { + if (enable) { + value = value | airplaneMode; + } else { + value = value & ~airplaneMode; + } + } - public boolean equals(Object obj) { - if (obj instanceof Integer) { - return value == (Integer) obj; + public void setWifi(boolean enable) { + if (enable) { + value = value | wifi; + } else { + value = value & ~wifi; + } } - if (obj instanceof NetworkConnectionSetting) { - return value == ((NetworkConnectionSetting)obj).value; + + public void setData(boolean enable) { + if (enable) { + value = value | data; + } else { + value = value & ~data; + } } - else { - return false; + + public int hashCode() { + return value; } - } - public String toString() { - return "{ AirplaneMode: " + airplaneModeEnabled() + ", Wifi: " + wifiEnabled() + ", Data: " + dataEnabled() + "}"; - } + public boolean equals(Object obj) { + if (obj instanceof Integer) { + return value == (Integer) obj; + } + if (obj instanceof NetworkConnectionSetting) { + return value == ((NetworkConnectionSetting) obj).value; + } else { + return false; + } + } + + public String toString() { + return "{ AirplaneMode: " + airplaneModeEnabled() + ", Wifi: " + wifiEnabled() + ", Data: " + + dataEnabled() + "}"; + } } diff --git a/src/main/java/io/appium/java_client/NoSuchContextException.java b/src/main/java/io/appium/java_client/NoSuchContextException.java index ae7217ad2..76e859b2e 100644 --- a/src/main/java/io/appium/java_client/NoSuchContextException.java +++ b/src/main/java/io/appium/java_client/NoSuchContextException.java @@ -18,15 +18,14 @@ import org.openqa.selenium.NotFoundException; -@SuppressWarnings("serial") -public class NoSuchContextException extends NotFoundException { +@SuppressWarnings("serial") public class NoSuchContextException extends NotFoundException { - public NoSuchContextException(String reason) { - super(reason); - } + public NoSuchContextException(String reason) { + super(reason); + } - public NoSuchContextException(String reason, Throwable cause) { - super(reason, cause); - } + public NoSuchContextException(String reason, Throwable cause) { + super(reason, cause); + } -} \ No newline at end of file +} diff --git a/src/main/java/io/appium/java_client/PerformsTouchActions.java b/src/main/java/io/appium/java_client/PerformsTouchActions.java index c94f7fa6f..e131517f2 100644 --- a/src/main/java/io/appium/java_client/PerformsTouchActions.java +++ b/src/main/java/io/appium/java_client/PerformsTouchActions.java @@ -17,31 +17,29 @@ package io.appium.java_client; public interface PerformsTouchActions { - /** - * Performs a chain of touch actions, which together can be considered an - * entire gesture. See the Webriver 3 spec - * https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html - * - * It's more convenient to call the perform() method of the TouchAction - * object itself. - * - * @param touchAction - * A TouchAction object, which contains a list of individual - * touch actions to perform - * @return the same touch action object - */ - public TouchAction performTouchAction(TouchAction touchAction); + /** + * Performs a chain of touch actions, which together can be considered an + * entire gesture. See the Webriver 3 spec + * https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html + *

+ * It's more convenient to call the perform() method of the TouchAction + * object itself. + * + * @param touchAction A TouchAction object, which contains a list of individual + * touch actions to perform + * @return the same touch action object + */ + public TouchAction performTouchAction(TouchAction touchAction); - /** - * Performs multiple TouchAction gestures at the same time, to simulate - * multiple fingers/touch inputs. See the Webriver 3 spec - * https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html - * - * It's more convenient to call the perform() method of the MultiTouchAction - * object. - * - * @param multiAction - * the MultiTouchAction object to perform. - */ - public void performMultiTouchAction(MultiTouchAction multiAction); + /** + * Performs multiple TouchAction gestures at the same time, to simulate + * multiple fingers/touch inputs. See the Webriver 3 spec + * https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html + *

+ * It's more convenient to call the perform() method of the MultiTouchAction + * object. + * + * @param multiAction the MultiTouchAction object to perform. + */ + public void performMultiTouchAction(MultiTouchAction multiAction); } diff --git a/src/main/java/io/appium/java_client/ScrollsTo.java b/src/main/java/io/appium/java_client/ScrollsTo.java index dd37be117..140b9e8dc 100644 --- a/src/main/java/io/appium/java_client/ScrollsTo.java +++ b/src/main/java/io/appium/java_client/ScrollsTo.java @@ -21,18 +21,19 @@ public interface ScrollsTo { /** - * Scroll to an element which contains the given text. - * @param text description or text of an element scroll to - * - * @return an element that matches - */ + * Scroll to an element which contains the given text. + * + * @param text description or text of an element scroll to + * @return an element that matches + */ T scrollTo(String text); /** - * Scroll to an element with the given text. - * @param text description or text of an element scroll to - * @return an element that matches - */ + * Scroll to an element with the given text. + * + * @param text description or text of an element scroll to + * @return an element that matches + */ T scrollToExact(String text); } diff --git a/src/main/java/io/appium/java_client/SwipeElementDirection.java b/src/main/java/io/appium/java_client/SwipeElementDirection.java index 2a17b143b..4e0c53bbb 100644 --- a/src/main/java/io/appium/java_client/SwipeElementDirection.java +++ b/src/main/java/io/appium/java_client/SwipeElementDirection.java @@ -23,103 +23,89 @@ public enum SwipeElementDirection { /** * Up from the center of the lower */ - UP{ - @Override - int getStartX(Point center, Point location, Dimension size, int ignored) { + UP { + @Override int getStartX(Point center, Point location, Dimension size, int ignored) { return center.getX(); } - @Override - int getStartY(Point center, Point location, Dimension size, int offSet) { + @Override int getStartY(Point center, Point location, Dimension size, int offSet) { int result = location.getY() + size.getHeight() - offSet; checkYCoordinate(result, location, size, offSet); return result; } - @Override - int getEndX(Point center, Point location, Dimension size, int ignored) { + @Override int getEndX(Point center, Point location, Dimension size, int ignored) { return center.getX(); } - @Override - int getEndY(Point center, Point location, Dimension size, int offSet) { + @Override int getEndY(Point center, Point location, Dimension size, int offSet) { int result = location.getY() + offSet; checkYCoordinate(result, location, size, offSet); return result; } - @Override - void checkDirection(int x1, int y1, int x2, int y2) { + @Override void checkDirection(int x1, int y1, int x2, int y2) { if (y1 < y2) - throw new IllegalCoordinatesException("Y1 " + y1 + " and Y2 " + y2 + " are inconsistent. It looks like you are " + throw new IllegalCoordinatesException( + "Y1 " + y1 + " and Y2 " + y2 + " are inconsistent. It looks like you are " + "trying to perform the swiping down"); } }, /** * Down from the center of the upper */ - DOWN{ - - @Override - int getStartX(Point center, Point location, Dimension size, int offSet) { + DOWN { + @Override int getStartX(Point center, Point location, Dimension size, int offSet) { return center.getX(); } - @Override - int getStartY(Point center, Point location, Dimension size, int offSet) { + @Override int getStartY(Point center, Point location, Dimension size, int offSet) { return UP.getEndY(center, location, size, offSet); } - @Override - int getEndX(Point center, Point location, Dimension size, int offSet) { + @Override int getEndX(Point center, Point location, Dimension size, int offSet) { return center.getX(); } - @Override - int getEndY(Point center, Point location, Dimension size, int offSet) { + @Override int getEndY(Point center, Point location, Dimension size, int offSet) { return UP.getStartY(center, location, size, offSet); } - @Override - void checkDirection(int x1, int y1, int x2, int y2) { + @Override void checkDirection(int x1, int y1, int x2, int y2) { if (y1 > y2) - throw new IllegalCoordinatesException("Y1 " + y1 + " and Y2 " + y2 + " are inconsistent. It looks like you are " + throw new IllegalCoordinatesException( + "Y1 " + y1 + " and Y2 " + y2 + " are inconsistent. It looks like you are " + "trying to perform the swiping up"); } }, /** * To the left from the center of the rightmost */ - LEFT{ - - @Override - int getStartX(Point center, Point location, Dimension size, int offSet) { + LEFT { + @Override int getStartX(Point center, Point location, Dimension size, int offSet) { int result = location.getX() + size.getWidth() - offSet; checkXCoordinate(result, location, size, offSet); return result; } - @Override - int getStartY(Point center, Point location, Dimension size, int offSet) { + @Override int getStartY(Point center, Point location, Dimension size, int offSet) { return center.getY(); } - @Override - int getEndX(Point center, Point location, Dimension size, int offSet) { + @Override int getEndX(Point center, Point location, Dimension size, int offSet) { int result = location.getX() + offSet; checkXCoordinate(result, location, size, offSet); return result; } - @Override - int getEndY(Point center, Point location, Dimension size, int offSet) { + @Override int getEndY(Point center, Point location, Dimension size, int offSet) { return center.getY(); } - @Override - void checkDirection(int x1, int y1, int x2, int y2) { + @Override void checkDirection(int x1, int y1, int x2, int y2) { if (x1 < x2) - throw new IllegalCoordinatesException("X1 " + x1 + " and X2 " + x2 + " are inconsistent. It looks like you are " + throw new IllegalCoordinatesException( + "X1 " + x1 + " and X2 " + x2 + " are inconsistent. It looks like you are " + "trying to perform the swiping right"); } @@ -127,44 +113,69 @@ void checkDirection(int x1, int y1, int x2, int y2) { /** * To the right from the center of the leftmost */ - RIGHT{ - - @Override - int getStartX(Point center, Point location, Dimension size, int offSet) { + RIGHT { + @Override int getStartX(Point center, Point location, Dimension size, int offSet) { return LEFT.getEndX(center, location, size, offSet); } - @Override - int getStartY(Point center, Point location, Dimension size, int offSet) { + @Override int getStartY(Point center, Point location, Dimension size, int offSet) { return center.getY(); } - @Override - int getEndX(Point center, Point location, Dimension size, int offSet) { + @Override int getEndX(Point center, Point location, Dimension size, int offSet) { return LEFT.getStartX(center, location, size, offSet); } - @Override - int getEndY(Point center, Point location, Dimension size, int offSet) { + @Override int getEndY(Point center, Point location, Dimension size, int offSet) { return center.getY(); } - @Override - void checkDirection(int x1, int y1, int x2, int y2) { + @Override void checkDirection(int x1, int y1, int x2, int y2) { if (x1 > x2) - throw new IllegalCoordinatesException("X1 " + x1 + " and X2 " + x2 + " are inconsistent. It looks like you are " + throw new IllegalCoordinatesException( + "X1 " + x1 + " and X2 " + x2 + " are inconsistent. It looks like you are " + "trying to perform the swiping left"); } }; + static void checkYCoordinate(int y, Point location, Dimension size, int offSet) + throws IllegalCoordinatesException { + int bottom = location.getY() + size.getHeight(); + int top = location.getY(); + if (y > bottom) + throw new IllegalCoordinatesException( + "The result Y " + y + " is lower than target element bottom " + bottom); + if (y < top) + throw new IllegalCoordinatesException( + "The result Y " + y + " is higher than target element top " + top); + + } + + static void checkXCoordinate(int x, Point location, Dimension size, int offSet) + throws IllegalCoordinatesException { + int right = location.getX() + size.getWidth(); + int left = location.getX(); + if (x > right) + throw new IllegalCoordinatesException( + "The result X " + x + " is righter than target element right border " + right); + if (x < left) + throw new IllegalCoordinatesException( + "The result X " + x + " is lefter than target element left border " + left); + + } + abstract int getStartX(Point center, Point location, Dimension size, int offSet); + abstract int getStartY(Point center, Point location, Dimension size, int offSet); + abstract int getEndX(Point center, Point location, Dimension size, int offSet); + abstract int getEndY(Point center, Point location, Dimension size, int offSet); + abstract void checkDirection(int x1, int y1, int x2, int y2); - void swipe(AppiumDriver driver, MobileElement element, - int offset1, int offset2, int duration) throws IllegalCoordinatesException{ + void swipe(AppiumDriver driver, MobileElement element, int offset1, int offset2, + int duration) throws IllegalCoordinatesException { Point p = element.getCenter(); Point location = element.getLocation(); Dimension size = element.getSize(); @@ -176,30 +187,4 @@ void swipe(AppiumDriver driver, MobileElement element, driver.swipe(startX, startY, endX, endY, duration); } - - static void checkYCoordinate(int y, Point location, Dimension size, int offSet) - throws IllegalCoordinatesException { - int bottom = location.getY() + size.getHeight(); - int top = location.getY(); - if (y > bottom) - throw new IllegalCoordinatesException("The result Y " + y + " is lower than target element bottom " - + bottom); - if (y < top) - throw new IllegalCoordinatesException("The result Y " + y + " is higher than target element top " - + top); - - } - - static void checkXCoordinate(int x, Point location, Dimension size, int offSet) - throws IllegalCoordinatesException { - int right = location.getX() + size.getWidth(); - int left = location.getX(); - if (x > right) - throw new IllegalCoordinatesException("The result X " + x + " is righter than target element right border " - + right); - if (x < left) - throw new IllegalCoordinatesException("The result X " + x + " is lefter than target element left border " - + left); - - } } diff --git a/src/main/java/io/appium/java_client/TouchAction.java b/src/main/java/io/appium/java_client/TouchAction.java index 6e34c6368..f6d20837b 100644 --- a/src/main/java/io/appium/java_client/TouchAction.java +++ b/src/main/java/io/appium/java_client/TouchAction.java @@ -25,327 +25,345 @@ /** * Used for Webdriver 3 touch actions * See the Webriver 3 spec https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html - * + *

* The flow is to chain individual touch actions into an entire gesture. e.g. - * TouchAction action = new TouchAction(driver); - * action.press(element).waitAction(300).moveTo(element1).release().perform(); - * + * TouchAction action = new TouchAction(driver); + * action.press(element).waitAction(300).moveTo(element1).release().perform(); + *

* Calling perform() sends the action command to the Mobile Driver. Otherwise, more and more actions can be chained. */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class TouchAction { - - private MobileDriver driver; - ImmutableList.Builder parameterBuilder; - - public TouchAction(MobileDriver driver) { - this.driver = driver; - parameterBuilder = ImmutableList.builder(); - } - - /** - * Press on the center of an element. - * @param el element to press on - * @return this TouchAction, for chaining - */ - public TouchAction press(WebElement el) { - ActionParameter action = new ActionParameter("press", (RemoteWebElement)el); - parameterBuilder.add(action); - return this; - } - - /** - * Press on an absolute position on the screen - * @param x x coordinate - * @param y y coordinate - * @return this TouchAction, for chaining - */ - public TouchAction press(int x, int y) { - ActionParameter action = new ActionParameter("press"); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Press on an element, offset from upper left corner by a number of pixels - * @param el element to press on - * @param x x offset - * @param y y offset - * @return this TouchAction, for chaining - */ - public TouchAction press(WebElement el, int x, int y) { - ActionParameter action = new ActionParameter("press", (RemoteWebElement)el); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Remove the current touching implement from the screen (withdraw your touch) - * @return this TouchAction, for chaining - */ - public TouchAction release() { - ActionParameter action = new ActionParameter("release"); - parameterBuilder.add(action); - return this; - } - - /** - * Move current touch to center of an element. - * @param el element to move to - * @return this TouchAction, for chaining - */ - public TouchAction moveTo(WebElement el) { - ActionParameter action = new ActionParameter("moveTo", (RemoteWebElement)el); - parameterBuilder.add(action); - return this; - } - - /** - * Move current touch to a new position relative to the current position on - * the screen. If the current position of this TouchAction is (xOld, yOld), - * then this method will move the TouchAction to (xOld + x, yOld + y). - * @param x change in x coordinate to move through - * @param y change in y coordinate to move through - * @return this TouchAction, for chaining - */ - public TouchAction moveTo(int x, int y) { - ActionParameter action = new ActionParameter("moveTo"); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Move current touch to an element, offset from upper left corner - * @param el element to move current touch to - * @param x x offset - * @param y y offset - * @return this TouchAction, for chaining - */ - public TouchAction moveTo(WebElement el, int x, int y) { - ActionParameter action = new ActionParameter("moveTo", (RemoteWebElement)el); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Tap the center of an element. - * @param el element to tap - * @return this TouchAction, for chaining - */ - public TouchAction tap(WebElement el) { - ActionParameter action = new ActionParameter("tap", (RemoteWebElement)el); - parameterBuilder.add(action); - return this; - } - - /** - * Tap an absolute position on the screen - * @param x x coordinate - * @param y y coordinate - * @return this TouchAction, for chaining - */ - public TouchAction tap(int x, int y) { - ActionParameter action = new ActionParameter("tap"); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Tap an element, offset from upper left corner - * @param el element to tap - * @param x x offset - * @param y y offset - * @return this TouchAction, for chaining - */ - public TouchAction tap(WebElement el, int x, int y) { - ActionParameter action = new ActionParameter("tap", (RemoteWebElement)el); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * A wait action, used as a NOP in multi-chaining - * - * @return this TouchAction, for chaining - */ - public TouchAction waitAction() { - ActionParameter action = new ActionParameter("wait"); - parameterBuilder.add(action); - return this; - } - - /** - * Waits for specified amount of time to pass before continue to next touch action - * @param ms time in milliseconds to wait - * @return this TouchAction, for chaining - */ - public TouchAction waitAction(int ms) { - ActionParameter action = new ActionParameter("wait"); - action.addParameter("ms", ms); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at the center of an element until the contextmenu event has fired. - * @param el element to long-press - * @return this TouchAction, for chaining - */ - public TouchAction longPress(WebElement el) { - ActionParameter action = new ActionParameter("longPress", (RemoteWebElement)el); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at the center of an element until the contextmenu event has fired. - * @param el element to long-press - * @param duration of the long-press, in milliseconds - * @return this TouchAction, for chaining - */ - public TouchAction longPress(WebElement el, int duration) { - ActionParameter action = new ActionParameter("longPress", (RemoteWebElement)el); - action.addParameter("duration", duration); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at an absolute position on the screen until the contextmenu event has fired. - * @param x x coordinate - * @param y y coordinate - * @return this TouchAction, for chaining - */ - public TouchAction longPress(int x, int y) { - ActionParameter action = new ActionParameter("longPress"); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at an absolute position on the screen until the contextmenu event has fired. - * @param x x coordinate - * @param y y coordinate - * @param duration of the long-press, in milliseconds - * @return this TouchAction, for chaining - */ - public TouchAction longPress(int x, int y, int duration) { - ActionParameter action = new ActionParameter("longPress"); - action.addParameter("x", x); - action.addParameter("y", y); - action.addParameter("duration", duration); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at an elements upper-left corner, offset by the given amount, until the contextmenu event has fired. - * @param el element to long-press - * @param x x offset - * @param y y offset - * @return this TouchAction, for chaining - */ - public TouchAction longPress(WebElement el, int x, int y) { - ActionParameter action = new ActionParameter("longPress", (RemoteWebElement)el); - action.addParameter("x", x); - action.addParameter("y", y); - parameterBuilder.add(action); - return this; - } - - /** - * Press and hold the at an elements upper-left corner, offset by the given amount, until the contextmenu event has fired. - * @param el element to long-press - * @param x x offset - * @param y y offset - * @param duration of the long-press, in milliseconds - * @return this TouchAction, for chaining - */ - public TouchAction longPress(WebElement el, int x, int y, int duration) { - ActionParameter action = new ActionParameter("longPress", (RemoteWebElement)el); - action.addParameter("x", x); - action.addParameter("y", y); - action.addParameter("duration", duration); - parameterBuilder.add(action); - return this; - } - - /** - * Cancel this action, if it was partially completed by the driver - */ - public void cancel() { - ActionParameter action = new ActionParameter("wait"); - parameterBuilder.add(action); - this.perform(); - } - - /** - * Perform this chain of actions on the driver. - * @return this TouchAction, for possible segmented-touches. - */ - public TouchAction perform() { - driver.performTouchAction(this); - return this; - } - - /** - * Get the mjsonwp parameters for this Action - * @return A map of parameters for this touch action to pass as part of mjsonwp - */ - protected ImmutableMap getParameters() { - - ImmutableList.Builder parameters = ImmutableList.builder(); - ImmutableList actionList = parameterBuilder.build(); - for (ActionParameter action : actionList){ - parameters.add(action.getParameterMap()); +@SuppressWarnings({"rawtypes", "unchecked"}) public class TouchAction { + + ImmutableList.Builder parameterBuilder; + private MobileDriver driver; + + public TouchAction(MobileDriver driver) { + this.driver = driver; + parameterBuilder = ImmutableList.builder(); + } + + /** + * Press on the center of an element. + * + * @param el element to press on + * @return this TouchAction, for chaining + */ + public TouchAction press(WebElement el) { + ActionParameter action = new ActionParameter("press", (RemoteWebElement) el); + parameterBuilder.add(action); + return this; + } + + /** + * Press on an absolute position on the screen + * + * @param x x coordinate + * @param y y coordinate + * @return this TouchAction, for chaining + */ + public TouchAction press(int x, int y) { + ActionParameter action = new ActionParameter("press"); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Press on an element, offset from upper left corner by a number of pixels + * + * @param el element to press on + * @param x x offset + * @param y y offset + * @return this TouchAction, for chaining + */ + public TouchAction press(WebElement el, int x, int y) { + ActionParameter action = new ActionParameter("press", (RemoteWebElement) el); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Remove the current touching implement from the screen (withdraw your touch) + * + * @return this TouchAction, for chaining + */ + public TouchAction release() { + ActionParameter action = new ActionParameter("release"); + parameterBuilder.add(action); + return this; + } + + /** + * Move current touch to center of an element. + * + * @param el element to move to + * @return this TouchAction, for chaining + */ + public TouchAction moveTo(WebElement el) { + ActionParameter action = new ActionParameter("moveTo", (RemoteWebElement) el); + parameterBuilder.add(action); + return this; + } + + /** + * Move current touch to a new position relative to the current position on + * the screen. If the current position of this TouchAction is (xOld, yOld), + * then this method will move the TouchAction to (xOld + x, yOld + y). + * + * @param x change in x coordinate to move through + * @param y change in y coordinate to move through + * @return this TouchAction, for chaining + */ + public TouchAction moveTo(int x, int y) { + ActionParameter action = new ActionParameter("moveTo"); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Move current touch to an element, offset from upper left corner + * + * @param el element to move current touch to + * @param x x offset + * @param y y offset + * @return this TouchAction, for chaining + */ + public TouchAction moveTo(WebElement el, int x, int y) { + ActionParameter action = new ActionParameter("moveTo", (RemoteWebElement) el); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Tap the center of an element. + * + * @param el element to tap + * @return this TouchAction, for chaining + */ + public TouchAction tap(WebElement el) { + ActionParameter action = new ActionParameter("tap", (RemoteWebElement) el); + parameterBuilder.add(action); + return this; + } + + /** + * Tap an absolute position on the screen + * + * @param x x coordinate + * @param y y coordinate + * @return this TouchAction, for chaining + */ + public TouchAction tap(int x, int y) { + ActionParameter action = new ActionParameter("tap"); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; } - return ImmutableMap.of("actions", parameters.build()); - } - - protected void clearParameters() { - parameterBuilder = ImmutableList.builder(); - } - - /** - * Just holds values to eventually return the parameters required for the mjsonwp - */ - private class ActionParameter { - private String actionName; - private ImmutableMap.Builder optionsBuilder; - - public ActionParameter(String actionName) { - this.actionName = actionName; - optionsBuilder = ImmutableMap.builder(); + + /** + * Tap an element, offset from upper left corner + * + * @param el element to tap + * @param x x offset + * @param y y offset + * @return this TouchAction, for chaining + */ + public TouchAction tap(WebElement el, int x, int y) { + ActionParameter action = new ActionParameter("tap", (RemoteWebElement) el); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * A wait action, used as a NOP in multi-chaining + * + * @return this TouchAction, for chaining + */ + public TouchAction waitAction() { + ActionParameter action = new ActionParameter("wait"); + parameterBuilder.add(action); + return this; + } + + /** + * Waits for specified amount of time to pass before continue to next touch action + * + * @param ms time in milliseconds to wait + * @return this TouchAction, for chaining + */ + public TouchAction waitAction(int ms) { + ActionParameter action = new ActionParameter("wait"); + action.addParameter("ms", ms); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at the center of an element until the contextmenu event has fired. + * + * @param el element to long-press + * @return this TouchAction, for chaining + */ + public TouchAction longPress(WebElement el) { + ActionParameter action = new ActionParameter("longPress", (RemoteWebElement) el); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at the center of an element until the contextmenu event has fired. + * + * @param el element to long-press + * @param duration of the long-press, in milliseconds + * @return this TouchAction, for chaining + */ + public TouchAction longPress(WebElement el, int duration) { + ActionParameter action = new ActionParameter("longPress", (RemoteWebElement) el); + action.addParameter("duration", duration); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at an absolute position on the screen until the contextmenu event has fired. + * + * @param x x coordinate + * @param y y coordinate + * @return this TouchAction, for chaining + */ + public TouchAction longPress(int x, int y) { + ActionParameter action = new ActionParameter("longPress"); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at an absolute position on the screen until the contextmenu event has fired. + * + * @param x x coordinate + * @param y y coordinate + * @param duration of the long-press, in milliseconds + * @return this TouchAction, for chaining + */ + public TouchAction longPress(int x, int y, int duration) { + ActionParameter action = new ActionParameter("longPress"); + action.addParameter("x", x); + action.addParameter("y", y); + action.addParameter("duration", duration); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at an elements upper-left corner, offset by the given amount, until the contextmenu event has fired. + * + * @param el element to long-press + * @param x x offset + * @param y y offset + * @return this TouchAction, for chaining + */ + public TouchAction longPress(WebElement el, int x, int y) { + ActionParameter action = new ActionParameter("longPress", (RemoteWebElement) el); + action.addParameter("x", x); + action.addParameter("y", y); + parameterBuilder.add(action); + return this; + } + + /** + * Press and hold the at an elements upper-left corner, offset by the given amount, until the contextmenu event has fired. + * + * @param el element to long-press + * @param x x offset + * @param y y offset + * @param duration of the long-press, in milliseconds + * @return this TouchAction, for chaining + */ + public TouchAction longPress(WebElement el, int x, int y, int duration) { + ActionParameter action = new ActionParameter("longPress", (RemoteWebElement) el); + action.addParameter("x", x); + action.addParameter("y", y); + action.addParameter("duration", duration); + parameterBuilder.add(action); + return this; + } + + /** + * Cancel this action, if it was partially completed by the driver + */ + public void cancel() { + ActionParameter action = new ActionParameter("wait"); + parameterBuilder.add(action); + this.perform(); + } + + /** + * Perform this chain of actions on the driver. + * + * @return this TouchAction, for possible segmented-touches. + */ + public TouchAction perform() { + driver.performTouchAction(this); + return this; } - public ActionParameter(String actionName, RemoteWebElement el) { - this.actionName = actionName; - optionsBuilder = ImmutableMap.builder(); - addParameter("element", el.getId()); + /** + * Get the mjsonwp parameters for this Action + * + * @return A map of parameters for this touch action to pass as part of mjsonwp + */ + protected ImmutableMap getParameters() { + + ImmutableList.Builder parameters = ImmutableList.builder(); + ImmutableList actionList = parameterBuilder.build(); + for (ActionParameter action : actionList) { + parameters.add(action.getParameterMap()); + } + return ImmutableMap.of("actions", parameters.build()); } - public ImmutableMap getParameterMap() { - ImmutableMap.Builder builder = ImmutableMap.builder(); - builder.put("action", actionName).put("options", optionsBuilder.build()); - return builder.build(); + protected void clearParameters() { + parameterBuilder = ImmutableList.builder(); } - public void addParameter(String name, Object value) { - optionsBuilder.put(name, value); + /** + * Just holds values to eventually return the parameters required for the mjsonwp + */ + private class ActionParameter { + private String actionName; + private ImmutableMap.Builder optionsBuilder; + + public ActionParameter(String actionName) { + this.actionName = actionName; + optionsBuilder = ImmutableMap.builder(); + } + + public ActionParameter(String actionName, RemoteWebElement el) { + this.actionName = actionName; + optionsBuilder = ImmutableMap.builder(); + addParameter("element", el.getId()); + } + + public ImmutableMap getParameterMap() { + ImmutableMap.Builder builder = ImmutableMap.builder(); + builder.put("action", actionName).put("options", optionsBuilder.build()); + return builder.build(); + } + + public void addParameter(String name, Object value) { + optionsBuilder.put(name, value); + } } - } } diff --git a/src/main/java/io/appium/java_client/TouchShortcuts.java b/src/main/java/io/appium/java_client/TouchShortcuts.java index 92e4c7153..346a8020b 100644 --- a/src/main/java/io/appium/java_client/TouchShortcuts.java +++ b/src/main/java/io/appium/java_client/TouchShortcuts.java @@ -21,39 +21,36 @@ public interface TouchShortcuts { /** - * Convenience method for "zooming in" on an element on the screen. - * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. - * NOTE: - * This convenience method slides touches away from the element, if this would happen to place one of them - * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param x x coordinate to start zoom on - * @param y y coordinate to start zoom on - */ + * Convenience method for "zooming in" on an element on the screen. + * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. + * NOTE: + * This convenience method slides touches away from the element, if this would happen to place one of them + * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param x x coordinate to start zoom on + * @param y y coordinate to start zoom on + */ void zoom(int x, int y); /** - * Convenience method for "zooming in" on an element on the screen. - * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. - * NOTE: - * This convenience method slides touches away from the element, if this would happen to place one of them - * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param el The element to pinch - */ + * Convenience method for "zooming in" on an element on the screen. + * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. + * NOTE: + * This convenience method slides touches away from the element, if this would happen to place one of them + * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param el The element to pinch + */ void zoom(WebElement el); /** * Convenience method for tapping a position on the screen * - * @param fingers - * number of fingers/appendages to tap with - * @param x - * x coordinate - * @param y - * y coordinate + * @param fingers number of fingers/appendages to tap with + * @param x x coordinate + * @param y y coordinate * @param duration how long between pressing down, and lifting fingers/appendages */ void tap(int fingers, int x, int y, int duration); @@ -61,55 +58,47 @@ public interface TouchShortcuts { /** * Convenience method for tapping the center of an element on the screen * - * @param fingers - * number of fingers/appendages to tap with - * @param element - * element to tap - * @param duration - * how long between pressing down, and lifting fingers/appendages + * @param fingers number of fingers/appendages to tap with + * @param element element to tap + * @param duration how long between pressing down, and lifting fingers/appendages */ void tap(int fingers, WebElement element, int duration); /** * Convenience method for swiping across the screen * - * @param startx - * starting x coordinate - * @param starty - * starting y coordinate - * @param endx - * ending x coordinate - * @param endy - * ending y coordinate - * @param duration - * amount of time in milliseconds for the entire swipe action to - * take + * @param startx starting x coordinate + * @param starty starting y coordinate + * @param endx ending x coordinate + * @param endy ending y coordinate + * @param duration amount of time in milliseconds for the entire swipe action to + * take */ void swipe(int startx, int starty, int endx, int endy, int duration); /** - * Convenience method for pinching an element on the screen. - * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. - * NOTE: - * This convenience method places the initial touches around the element at a distance, if this would happen to place - * one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the - * MultiTouchAction api instead of this method. - * - * @param x x coordinate to terminate the pinch on - * @param y y coordinate to terminate the pinch on - */ + * Convenience method for pinching an element on the screen. + * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. + * NOTE: + * This convenience method places the initial touches around the element at a distance, if this would happen to place + * one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the + * MultiTouchAction api instead of this method. + * + * @param x x coordinate to terminate the pinch on + * @param y y coordinate to terminate the pinch on + */ void pinch(int x, int y); /** - * Convenience method for pinching an element on the screen. - * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. - * NOTE: - * This convenience method places the initial touches around the element, if this would happen to place one of them - * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - * @param el The element to pinch - */ + * Convenience method for pinching an element on the screen. + * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. + * NOTE: + * This convenience method places the initial touches around the element, if this would happen to place one of them + * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + * + * @param el The element to pinch + */ void pinch(WebElement el); } diff --git a/src/main/java/io/appium/java_client/TouchableElement.java b/src/main/java/io/appium/java_client/TouchableElement.java index 8379d0e4b..a3c071dbb 100644 --- a/src/main/java/io/appium/java_client/TouchableElement.java +++ b/src/main/java/io/appium/java_client/TouchableElement.java @@ -25,71 +25,64 @@ public interface TouchableElement extends WebElement { /** - * Convenience method for pinching the given element. - * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. - * NOTE: - * This convenience method places the initial touches around the element, if this would happen to place one of them - * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - * - */ + * Convenience method for pinching the given element. + * "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. + * NOTE: + * This convenience method places the initial touches around the element, if this would happen to place one of them + * off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + */ void pinch(); /** * Convenience method for tapping the center of the given element * - * @param fingers - * number of fingers/appendages to tap with - * @param duration - * how long between pressing down, and lifting fingers/appendages + * @param fingers number of fingers/appendages to tap with + * @param duration how long between pressing down, and lifting fingers/appendages */ void tap(int fingers, int duration); /** - * Convenience method for "zooming in" on the given element. - * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. - * NOTE: - * This convenience method slides touches away from the element, if this would happen to place one of them - * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api - * instead of this method. - */ - void zoom(); + * Convenience method for "zooming in" on the given element. + * "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. + * NOTE: + * This convenience method slides touches away from the element, if this would happen to place one of them + * off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api + * instead of this method. + */ + void zoom(); - /** - * Convenience method for swiping on the given element to the given direction - * - * @param direction UP, DOWN, LEFT, RIGHT - * - * @param duration amount of time in milliseconds for the entire swipe action to - * take - */ - void swipe(SwipeElementDirection direction, int duration); + /** + * Convenience method for swiping on the given element to the given direction + * + * @param direction UP, DOWN, LEFT, RIGHT + * @param duration amount of time in milliseconds for the entire swipe action to + * take + */ + void swipe(SwipeElementDirection direction, int duration); - /** - * Convenience method for swiping on the given element to the given direction - * - * @param direction direction UP, DOWN, LEFT, RIGHT - * - * @param offsetFromEndBorder is the offset from the border of the element where the swiping should be started. - * If direction is UP then - * this is offset from the bottom of the element. If direction is DOWN then - * this is offset from the top of the element. If direction is RIGHT then - * this is offset from the left border of the element. If direction is LEFT then - * this is offset from the right border of the element. - * - * @param offsetFromEndBorder is the offset from the border of the element where the swiping should be finished. - * If direction is UP then - * this is offset from the top of the element. If direction is DOWN then - * this is offset from the bottom of the element. If direction is RIGHT then - * this is offset from the right border of the element. If direction is LEFT then - * this is offset from the left border of the element. - * - * @param duration amount of time in milliseconds for the entire swipe action to - * take - * @throws IllegalCoordinatesException when resulted coordinates are out of the element borders - * or disagree with the given direction - */ - void swipe(SwipeElementDirection direction, int offsetFromStartBorder, - int offsetFromEndBorder, int duration) throws IllegalCoordinatesException; + /** + * Convenience method for swiping on the given element to the given direction + * + * @param direction direction UP, DOWN, LEFT, RIGHT + * @param offsetFromEndBorder is the offset from the border of the element where the swiping should be started. + * If direction is UP then + * this is offset from the bottom of the element. If direction is DOWN then + * this is offset from the top of the element. If direction is RIGHT then + * this is offset from the left border of the element. If direction is LEFT then + * this is offset from the right border of the element. + * @param offsetFromEndBorder is the offset from the border of the element where the swiping should be finished. + * If direction is UP then + * this is offset from the top of the element. If direction is DOWN then + * this is offset from the bottom of the element. If direction is RIGHT then + * this is offset from the right border of the element. If direction is LEFT then + * this is offset from the left border of the element. + * @param duration amount of time in milliseconds for the entire swipe action to + * take + * @throws IllegalCoordinatesException when resulted coordinates are out of the element borders + * or disagree with the given direction + */ + void swipe(SwipeElementDirection direction, int offsetFromStartBorder, int offsetFromEndBorder, + int duration) throws IllegalCoordinatesException; } diff --git a/src/main/java/io/appium/java_client/android/AndroidDeviceActionShortcuts.java b/src/main/java/io/appium/java_client/android/AndroidDeviceActionShortcuts.java index 969ae96e2..88014fd7e 100644 --- a/src/main/java/io/appium/java_client/android/AndroidDeviceActionShortcuts.java +++ b/src/main/java/io/appium/java_client/android/AndroidDeviceActionShortcuts.java @@ -23,8 +23,7 @@ public interface AndroidDeviceActionShortcuts extends DeviceActionShortcuts { /** * Send a key event to the device * - * @param key - * code for the key pressed on the device + * @param key code for the key pressed on the device */ void pressKeyCode(int key); @@ -32,9 +31,8 @@ public interface AndroidDeviceActionShortcuts extends DeviceActionShortcuts { * Send a key event along with an Android metastate to an Android device * Metastates are things like *shift* to get uppercase characters * - * @param key code for the key pressed on the Android device + * @param key code for the key pressed on the Android device * @param metastate metastate for the keypress - * * @see AndroidKeyCode * @see AndroidKeyMetastate */ @@ -43,8 +41,7 @@ public interface AndroidDeviceActionShortcuts extends DeviceActionShortcuts { /** * Send a long key event to the device * - * @param key - * code for the key pressed on the device + * @param key code for the key pressed on the device */ void longPressKeyCode(int key); @@ -52,9 +49,8 @@ public interface AndroidDeviceActionShortcuts extends DeviceActionShortcuts { * Send a long key event along with an Android metastate to an Android device * Metastates are things like *shift* to get uppercase characters * - * @param key code for the key pressed on the Android device + * @param key code for the key pressed on the Android device * @param metastate metastate for the keypress - * * @see AndroidKeyCode * @see AndroidKeyMetastate */ diff --git a/src/main/java/io/appium/java_client/android/AndroidDriver.java b/src/main/java/io/appium/java_client/android/AndroidDriver.java index b201e6827..6cb34347d 100644 --- a/src/main/java/io/appium/java_client/android/AndroidDriver.java +++ b/src/main/java/io/appium/java_client/android/AndroidDriver.java @@ -17,7 +17,6 @@ package io.appium.java_client.android; import com.google.common.collect.ImmutableMap; - import io.appium.java_client.AppiumDriver; import io.appium.java_client.AppiumSetting; import io.appium.java_client.FindsByAndroidUIAutomator; @@ -30,32 +29,29 @@ import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.Response; +import org.openqa.selenium.remote.http.HttpClient; import java.net.URL; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static io.appium.java_client.MobileCommand.*; -import static io.appium.java_client.remote.MobileCapabilityType.APP_ACTIVITY; -import static io.appium.java_client.remote.MobileCapabilityType.APP_PACKAGE; -import static io.appium.java_client.remote.MobileCapabilityType.APP_WAIT_ACTIVITY; -import static io.appium.java_client.remote.MobileCapabilityType.APP_WAIT_PACKAGE; -import static io.appium.java_client.remote.MobileCapabilityType.DONT_STOP_APP_ON_RESET; -import org.openqa.selenium.remote.http.HttpClient; +import static io.appium.java_client.remote.MobileCapabilityType.*; /** * @param the required type of class which implement {@link org.openqa.selenium.WebElement}. - * Instances of the defined type will be returned via findElement* and findElements*. - * Warning (!!!). Allowed types: - * {@link org.openqa.selenium.WebElement} - * {@link io.appium.java_client.TouchableElement} - * {@link org.openqa.selenium.remote.RemoteWebElement} - * {@link io.appium.java_client.MobileElement} - * {@link io.appium.java_client.android.AndroidElement} + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} + * {@link io.appium.java_client.android.AndroidElement} */ -public class AndroidDriver extends AppiumDriver implements - AndroidDeviceActionShortcuts, HasNetworkConnection, PushesFiles, - StartsActivity, FindsByAndroidUIAutomator { +public class AndroidDriver + extends AppiumDriver + implements AndroidDeviceActionShortcuts, HasNetworkConnection, PushesFiles, StartsActivity, + FindsByAndroidUIAutomator { private static final String ANDROID_PLATFORM = MobilePlatform.ANDROID; @@ -68,254 +64,214 @@ public class AndroidDriver extends Appiu private final String CONNECTION_NAME_VALUE = "network_connection"; public AndroidDriver(URL remoteAddress, Capabilities desiredCapabilities) { - super(remoteAddress, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + super(remoteAddress, substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - - public AndroidDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(remoteAddress, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + + public AndroidDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(remoteAddress, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } public AndroidDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities) { - super(service, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + super(service, substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - - public AndroidDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(service, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + + public AndroidDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(service, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } public AndroidDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities) { - super(builder, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + super(builder, substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - - public AndroidDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(builder, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + + public AndroidDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(builder, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - + public AndroidDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(httpClientFactory, substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + super(httpClientFactory, substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - + public AndroidDriver(Capabilities desiredCapabilities) { - super(substituteMobilePlatform(desiredCapabilities, - ANDROID_PLATFORM)); + super(substituteMobilePlatform(desiredCapabilities, ANDROID_PLATFORM)); this.setElementConverter(new JsonToAndroidElementConverter(this)); } - @Override - public RequiredElementType scrollTo(String text) { - String uiScrollables = UiScrollable("new UiSelector().descriptionContains(\"" + text + "\")") + - UiScrollable("new UiSelector().textContains(\"" + text + "\")"); - return findElementByAndroidUIAutomator(uiScrollables); - } + static String UiScrollable(String uiSelector) { + return "new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(" + + uiSelector + ".instance(0));"; + } - @Override - public RequiredElementType scrollToExact(String text) { - String uiScrollables = UiScrollable("new UiSelector().description(\"" + text + "\")") + - UiScrollable("new UiSelector().text(\"" + text + "\")"); - return findElementByAndroidUIAutomator(uiScrollables); - } + @Override public RequiredElementType scrollTo(String text) { + String uiScrollables = + UiScrollable("new UiSelector().descriptionContains(\"" + text + "\")") + UiScrollable( + "new UiSelector().textContains(\"" + text + "\")"); + return findElementByAndroidUIAutomator(uiScrollables); + } - static String UiScrollable(String uiSelector) { - return "new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(" + uiSelector + ".instance(0));"; - } + @Override public RequiredElementType scrollToExact(String text) { + String uiScrollables = + UiScrollable("new UiSelector().description(\"" + text + "\")") + UiScrollable( + "new UiSelector().text(\"" + text + "\")"); + return findElementByAndroidUIAutomator(uiScrollables); + } /** * Send a key event to the device * - * @param key - * code for the key pressed on the device + * @param key code for the key pressed on the device */ - @Override - public void pressKeyCode(int key) { + @Override public void pressKeyCode(int key) { execute(PRESS_KEY_CODE, getCommandImmutableMap(KEY_CODE, key)); } - /** - * @param key - * code for the key pressed on the Android device - * @param metastate - * metastate for the keypress - * + /** + * @param key code for the key pressed on the Android device + * @param metastate metastate for the keypress * @see AndroidKeyCode * @see AndroidKeyMetastate * @see AndroidDeviceActionShortcuts#pressKeyCode(int, Integer) */ - @Override - public void pressKeyCode(int key, Integer metastate) { - String[] parameters = new String[] { KEY_CODE, METASTATE_PARAM }; - Object[] values = new Object[] { key, metastate }; + @Override public void pressKeyCode(int key, Integer metastate) { + String[] parameters = new String[] {KEY_CODE, METASTATE_PARAM}; + Object[] values = new Object[] {key, metastate}; execute(PRESS_KEY_CODE, getCommandImmutableMap(parameters, values)); } /** * Send a long key event to the device * - * @param key - * code for the long key pressed on the device + * @param key code for the long key pressed on the device */ - @Override - public void longPressKeyCode(int key) { + @Override public void longPressKeyCode(int key) { execute(LONG_PRESS_KEY_CODE, getCommandImmutableMap(KEY_CODE, key)); } /** - * @param key - * code for the long key pressed on the Android device - * @param metastate - * metastate for the long key press - * + * @param key code for the long key pressed on the Android device + * @param metastate metastate for the long key press * @see AndroidKeyCode * @see AndroidKeyMetastate * @see AndroidDeviceActionShortcuts#pressKeyCode(int, Integer) */ - @Override - public void longPressKeyCode(int key, Integer metastate) { - String[] parameters = new String[] { KEY_CODE, METASTATE_PARAM }; - Object[] values = new Object[] { key, metastate }; + @Override public void longPressKeyCode(int key, Integer metastate) { + String[] parameters = new String[] {KEY_CODE, METASTATE_PARAM}; + Object[] values = new Object[] {key, metastate}; execute(LONG_PRESS_KEY_CODE, getCommandImmutableMap(parameters, values)); } /** * @see HasNetworkConnection#getNetworkConnection() */ - @Override - public NetworkConnectionSetting getNetworkConnection() { + @Override public NetworkConnectionSetting getNetworkConnection() { Response response = execute(GET_NETWORK_CONNECTION); - return new NetworkConnectionSetting(Integer.parseInt(response - .getValue().toString())); + return new NetworkConnectionSetting(Integer.parseInt(response.getValue().toString())); } /** - * @param connection - * The NetworkConnectionSetting configuration to use for the - * device - * + * @param connection The NetworkConnectionSetting configuration to use for the + * device * @see HasNetworkConnection#setNetworkConnection(NetworkConnectionSetting) */ - @Override - public void setNetworkConnection(NetworkConnectionSetting connection) { + @Override public void setNetworkConnection(NetworkConnectionSetting connection) { // the new version of the webdriver protocol is going forward with // sending JSON message which look like // {name: "name of endpoint", parameters: "JSON parameters"} // this is for webdrivers which run on protocols besides HTTP (like TCP) // we're implementing that pattern here, for this new method, but // haven't translated it to all other commands yet - String[] parameters = new String[] { CONNECTION_NAME_PARAM, - CONNECTION_PARAM_PARAM }; - Object[] values = new Object[] { CONNECTION_NAME_VALUE, - ImmutableMap.of("type", connection.value) }; - execute(SET_NETWORK_CONNECTION, - getCommandImmutableMap(parameters, values)); + String[] parameters = new String[] {CONNECTION_NAME_PARAM, CONNECTION_PARAM_PARAM}; + Object[] values = + new Object[] {CONNECTION_NAME_VALUE, ImmutableMap.of("type", connection.value)}; + execute(SET_NETWORK_CONNECTION, getCommandImmutableMap(parameters, values)); } /** - * @param remotePath - * Path to file to write data to on remote device - * @param base64Data - * Base64 encoded byte array of data to write to remote device + * @param remotePath Path to file to write data to on remote device + * @param base64Data Base64 encoded byte array of data to write to remote device * @see PushesFiles#pushFile(String, byte[]) */ - @Override - public void pushFile(String remotePath, byte[] base64Data) { - String[] parameters = new String[] { PATH, DATA_PARAM }; - Object[] values = new Object[] { remotePath, base64Data }; + @Override public void pushFile(String remotePath, byte[] base64Data) { + String[] parameters = new String[] {PATH, DATA_PARAM}; + Object[] values = new Object[] {remotePath, base64Data}; execute(PUSH_FILE, getCommandImmutableMap(parameters, values)); } /** - * @param appPackage - * The package containing the activity. [Required] - * @param appActivity - * The activity to start. [Required] - * @param appWaitPackage - * Automation will begin after this package starts. [Optional] - * @param appWaitActivity - * Automation will begin after this activity starts. [Optional] - * @param stopApp - * If true, target app will be stopped. [Optional] + * @param appPackage The package containing the activity. [Required] + * @param appActivity The activity to start. [Required] + * @param appWaitPackage Automation will begin after this package starts. [Optional] + * @param appWaitActivity Automation will begin after this activity starts. [Optional] + * @param stopApp If true, target app will be stopped. [Optional] * @see StartsActivity#startActivity(String, String, String, String) */ - public void startActivity(String appPackage, String appActivity, - String appWaitPackage, String appWaitActivity, boolean stopApp) - throws IllegalArgumentException { + public void startActivity(String appPackage, String appActivity, String appWaitPackage, + String appWaitActivity, boolean stopApp) throws IllegalArgumentException { - checkArgument( - (_isNotNullOrEmpty(appPackage) && _isNotNullOrEmpty(appActivity)), - String.format("'%s' and '%s' are required.", APP_PACKAGE, - APP_ACTIVITY)); + checkArgument((_isNotNullOrEmpty(appPackage) && _isNotNullOrEmpty(appActivity)), + String.format("'%s' and '%s' are required.", APP_PACKAGE, APP_ACTIVITY)); - appWaitPackage = _isNotNullOrEmpty(appWaitPackage) ? appWaitPackage - : ""; - appWaitActivity = _isNotNullOrEmpty(appWaitActivity) ? appWaitActivity - : ""; + appWaitPackage = _isNotNullOrEmpty(appWaitPackage) ? appWaitPackage : ""; + appWaitActivity = _isNotNullOrEmpty(appWaitActivity) ? appWaitActivity : ""; - ImmutableMap parameters = ImmutableMap.of(APP_PACKAGE, - appPackage, APP_ACTIVITY, appActivity, APP_WAIT_PACKAGE, - appWaitPackage, APP_WAIT_ACTIVITY, appWaitActivity, - DONT_STOP_APP_ON_RESET, !stopApp); + ImmutableMap parameters = ImmutableMap + .of(APP_PACKAGE, appPackage, APP_ACTIVITY, appActivity, APP_WAIT_PACKAGE, + appWaitPackage, APP_WAIT_ACTIVITY, appWaitActivity, DONT_STOP_APP_ON_RESET, + !stopApp); execute(START_ACTIVITY, parameters); } /** - * @param appPackage - * The package containing the activity. [Required] - * @param appActivity - * The activity to start. [Required] - * @param appWaitPackage - * Automation will begin after this package starts. [Optional] - * @param appWaitActivity - * Automation will begin after this activity starts. [Optional] + * @param appPackage The package containing the activity. [Required] + * @param appActivity The activity to start. [Required] + * @param appWaitPackage Automation will begin after this package starts. [Optional] + * @param appWaitActivity Automation will begin after this activity starts. [Optional] * @see StartsActivity#startActivity(String, String, String, String) */ - public void startActivity(String appPackage, String appActivity, - String appWaitPackage, String appWaitActivity) - throws IllegalArgumentException { + public void startActivity(String appPackage, String appActivity, String appWaitPackage, + String appWaitActivity) throws IllegalArgumentException { this.startActivity(appPackage, appActivity, null, null, true); } /** - * @param appPackage The package containing the activity. [Required] + * @param appPackage The package containing the activity. [Required] * @param appActivity The activity to start. [Required] * @see StartsActivity#startActivity(String, String) */ - @Override - public void startActivity(String appPackage, String appActivity) - throws IllegalArgumentException { + @Override public void startActivity(String appPackage, String appActivity) + throws IllegalArgumentException { this.startActivity(appPackage, appActivity, null, null); } /** * Get test-coverage data * - * @param intent - * intent to broadcast - * @param path - * path to .ec file + * @param intent intent to broadcast + * @param path path to .ec file */ public void endTestCoverage(String intent, String path) { - String[] parameters = new String[] { INTENT_PARAM, PATH }; - Object[] values = new Object[] { intent, path }; + String[] parameters = new String[] {INTENT_PARAM, PATH}; + Object[] values = new Object[] {intent, path}; execute(END_TEST_COVERAGE, getCommandImmutableMap(parameters, values)); } /** * Get the current activity being run on the mobile device + * * @return a current activity being run on the mobile device */ public String currentActivity() { @@ -346,14 +302,13 @@ public void toggleLocationServices() { /** * Set the `ignoreUnimportantViews` setting. *Android-only method* - * + *

* Sets whether Android devices should use `setCompressedLayoutHeirarchy()` * which ignores all views which are marked IMPORTANT_FOR_ACCESSIBILITY_NO * or IMPORTANT_FOR_ACCESSIBILITY_AUTO (and have been deemed not important * by the system), in an attempt to make things less confusing or faster. * - * @param compress - * ignores unimportant views if true, doesn't ignore otherwise. + * @param compress ignores unimportant views if true, doesn't ignore otherwise. */ // Should be moved to the subclass public void ignoreUnimportantViews(Boolean compress) { @@ -363,18 +318,18 @@ public void ignoreUnimportantViews(Boolean compress) { /** * @throws org.openqa.selenium.WebDriverException This method is not applicable with browser/webview UI. */ - @SuppressWarnings("unchecked") - @Override - public RequiredElementType findElementByAndroidUIAutomator(String using) throws WebDriverException { + @SuppressWarnings("unchecked") @Override + public RequiredElementType findElementByAndroidUIAutomator(String using) + throws WebDriverException { return (RequiredElementType) findElement("-android uiautomator", using); } /** * @throws WebDriverException This method is not applicable with browser/webview UI. */ - @SuppressWarnings("unchecked") - @Override - public List findElementsByAndroidUIAutomator(String using) throws WebDriverException { + @SuppressWarnings("unchecked") @Override + public List findElementsByAndroidUIAutomator(String using) + throws WebDriverException { return (List) findElements("-android uiautomator", using); } diff --git a/src/main/java/io/appium/java_client/android/AndroidElement.java b/src/main/java/io/appium/java_client/android/AndroidElement.java index 92da9d9c8..8061cbc5b 100644 --- a/src/main/java/io/appium/java_client/android/AndroidElement.java +++ b/src/main/java/io/appium/java_client/android/AndroidElement.java @@ -16,45 +16,43 @@ package io.appium.java_client.android; -import java.util.ArrayList; -import java.util.List; - -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.WebElement; - import com.google.common.collect.ImmutableMap; import io.appium.java_client.FindsByAndroidUIAutomator; import io.appium.java_client.MobileCommand; import io.appium.java_client.MobileElement; +import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.WebElement; + +import java.util.ArrayList; +import java.util.List; -public class AndroidElement extends MobileElement implements - FindsByAndroidUIAutomator { +public class AndroidElement extends MobileElement + implements FindsByAndroidUIAutomator { /** * @throws org.openqa.selenium.WebDriverException This method is not applicable with browser/webview UI. */ - @Override - public MobileElement findElementByAndroidUIAutomator(String using) throws WebDriverException { + @Override public MobileElement findElementByAndroidUIAutomator(String using) + throws WebDriverException { return (MobileElement) findElement("-android uiautomator", using); } /** * @throws WebDriverException This method is not applicable with browser/webview UI. */ - @Override - public List findElementsByAndroidUIAutomator(String using) throws WebDriverException { + @Override public List findElementsByAndroidUIAutomator(String using) + throws WebDriverException { List result = new ArrayList(); List found = findElements("-android uiautomator", using); - for (WebElement e: found) + for (WebElement e : found) result.add((AndroidElement) e); return result; } - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void replaceValue(String value) { + @SuppressWarnings({"rawtypes", "unchecked"}) public void replaceValue(String value) { ImmutableMap.Builder builder = ImmutableMap.builder(); - builder.put("id", getId()).put("value", new String[] { value }); + builder.put("id", getId()).put("value", new String[] {value}); execute(MobileCommand.REPLACE_VALUE, builder.build()); } } diff --git a/src/main/java/io/appium/java_client/android/AndroidKeyCode.java b/src/main/java/io/appium/java_client/android/AndroidKeyCode.java index bfd43f491..66b7fc484 100644 --- a/src/main/java/io/appium/java_client/android/AndroidKeyCode.java +++ b/src/main/java/io/appium/java_client/android/AndroidKeyCode.java @@ -21,1270 +21,1270 @@ */ public interface AndroidKeyCode { - int BACK = 4; - int BACKSPACE = 67; - int DEL = 67; - int ENTER = 66; - int HOME = 3; - int MENU = 82; - int SETTINGS = 176; - int SPACE = 62; - - // getAction() value: the key has been pressed down. - // (0x00000000) - int ACTION_DOWN = 0; - - // getAction() value: multiple duplicate key events have occurred in a row, or a complex string is being delivered. If the key code is not {#link KEYCODE_UNKNOWN then the {#link getRepeatCount() method returns the number of times the given key code should be executed. Otherwise, if the key code is KEYCODE_UNKNOWN, then this is a sequence of characters as returned by getCharacters(). - // (0x00000002) - int ACTION_MULTIPLE = 2; - - // getAction() value: the key has been released. - // (0x00000001) - int ACTION_UP = 1; - - // When associated with up key events, this indicates that the key press has been canceled. Typically this is used with virtual touch screen keys, where the user can slide from the virtual key area on to the display: in that case, the application will receive a canceled up event and should not perform the action normally associated with the key. Note that for this to work, the application can not perform an action for a key until it receives an up or the long press timeout has expired. - // (0x00000020) - int FLAG_CANCELED = 32; - - // Set when a key event has FLAG_CANCELED set because a long press action was executed while it was down. - // (0x00000100) - int FLAG_CANCELED_LONG_PRESS = 256; - - // This mask is used for compatibility, to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done". This allows TextView to dispatch these as normal enter keys for old applications, but still do the appropriate action when receiving them. - // (0x00000010) - int FLAG_EDITOR_ACTION = 16; - - // Set when a key event has been synthesized to implement default behavior for an event that the application did not handle. Fallback key events are generated by unhandled trackball motions (to emulate a directional keypad) and by certain unhandled key presses that are declared in the key map (such as special function numeric keypad keys when numlock is off). - // (0x00000400) - int FLAG_FALLBACK = 1024; - - // This mask is set if an event was known to come from a trusted part of the system. That is, the event is known to come from the user, and could not have been spoofed by a third party component. - // (0x00000008) - int FLAG_FROM_SYSTEM = 8; - - // This mask is set if we don't want the key event to cause us to leave touch mode. - // (0x00000004) - int FLAG_KEEP_TOUCH_MODE = 4; - - // This flag is set for the first key repeat that occurs after the long press timeout. - // (0x00000080) - int FLAG_LONG_PRESS = 128; - - // This mask is set if the key event was generated by a software keyboard. - // (0x00000002) - int FLAG_SOFT_KEYBOARD = 2; - - // Set for ACTION_UP when this event's key code is still being tracked from its initial down. That is, somebody requested that tracking started on the key down and a long press has not caused the tracking to be canceled. - // (0x00000200) - int FLAG_TRACKING = 512; - - // This key event was generated by a virtual (on-screen) hard key area. Typically this is an area of the touchscreen, outside of the regular display, dedicated to "hardware" buttons. - // (0x00000040) - int FLAG_VIRTUAL_HARD_KEY = 64; - - // This constant was deprecated in API level 20. - // This flag will never be set by the system since the system consumes all wake keys itself. - // This mask is set if the device woke because of this key event. - // (0x00000001) - int FLAG_WOKE_HERE = 1; - - // Key code constant: '0' key. - // (0x00000007) - int KEYCODE_0 = 7; - - // Key code constant: '1' key. - // (0x00000008) - int KEYCODE_1 = 8; - - // Key code constant: '11' key. - // (0x000000e3) - int KEYCODE_11 = 227; - - // Key code constant: '12' key. - // (0x000000e4) - int KEYCODE_12 = 228; - - // Key code constant: '2' key. - // (0x00000009) - int KEYCODE_2 = 9; - - // Key code constant: '3' key. - // (0x0000000a) - int KEYCODE_3 = 10; - - // Key code constant: 3D Mode key. Toggles the display between 2D and 3D mode. - // (0x000000ce) - int KEYCODE_3D_MODE = 206; - - // Key code constant: '4' key. - // (0x0000000b) - int KEYCODE_4 = 11; - - // Key code constant: '5' key. - // (0x0000000c) - int KEYCODE_5 = 12; - - // Key code constant: '6' key. - // (0x0000000d) - int KEYCODE_6 = 13; + int BACK = 4; + int BACKSPACE = 67; + int DEL = 67; + int ENTER = 66; + int HOME = 3; + int MENU = 82; + int SETTINGS = 176; + int SPACE = 62; + + // getAction() value: the key has been pressed down. + // (0x00000000) + int ACTION_DOWN = 0; + + // getAction() value: multiple duplicate key events have occurred in a row, or a complex string is being delivered. If the key code is not {#link KEYCODE_UNKNOWN then the {#link getRepeatCount() method returns the number of times the given key code should be executed. Otherwise, if the key code is KEYCODE_UNKNOWN, then this is a sequence of characters as returned by getCharacters(). + // (0x00000002) + int ACTION_MULTIPLE = 2; + + // getAction() value: the key has been released. + // (0x00000001) + int ACTION_UP = 1; + + // When associated with up key events, this indicates that the key press has been canceled. Typically this is used with virtual touch screen keys, where the user can slide from the virtual key area on to the display: in that case, the application will receive a canceled up event and should not perform the action normally associated with the key. Note that for this to work, the application can not perform an action for a key until it receives an up or the long press timeout has expired. + // (0x00000020) + int FLAG_CANCELED = 32; + + // Set when a key event has FLAG_CANCELED set because a long press action was executed while it was down. + // (0x00000100) + int FLAG_CANCELED_LONG_PRESS = 256; + + // This mask is used for compatibility, to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done". This allows TextView to dispatch these as normal enter keys for old applications, but still do the appropriate action when receiving them. + // (0x00000010) + int FLAG_EDITOR_ACTION = 16; + + // Set when a key event has been synthesized to implement default behavior for an event that the application did not handle. Fallback key events are generated by unhandled trackball motions (to emulate a directional keypad) and by certain unhandled key presses that are declared in the key map (such as special function numeric keypad keys when numlock is off). + // (0x00000400) + int FLAG_FALLBACK = 1024; + + // This mask is set if an event was known to come from a trusted part of the system. That is, the event is known to come from the user, and could not have been spoofed by a third party component. + // (0x00000008) + int FLAG_FROM_SYSTEM = 8; + + // This mask is set if we don't want the key event to cause us to leave touch mode. + // (0x00000004) + int FLAG_KEEP_TOUCH_MODE = 4; + + // This flag is set for the first key repeat that occurs after the long press timeout. + // (0x00000080) + int FLAG_LONG_PRESS = 128; + + // This mask is set if the key event was generated by a software keyboard. + // (0x00000002) + int FLAG_SOFT_KEYBOARD = 2; + + // Set for ACTION_UP when this event's key code is still being tracked from its initial down. That is, somebody requested that tracking started on the key down and a long press has not caused the tracking to be canceled. + // (0x00000200) + int FLAG_TRACKING = 512; + + // This key event was generated by a virtual (on-screen) hard key area. Typically this is an area of the touchscreen, outside of the regular display, dedicated to "hardware" buttons. + // (0x00000040) + int FLAG_VIRTUAL_HARD_KEY = 64; + + // This constant was deprecated in API level 20. + // This flag will never be set by the system since the system consumes all wake keys itself. + // This mask is set if the device woke because of this key event. + // (0x00000001) + int FLAG_WOKE_HERE = 1; + + // Key code constant: '0' key. + // (0x00000007) + int KEYCODE_0 = 7; + + // Key code constant: '1' key. + // (0x00000008) + int KEYCODE_1 = 8; + + // Key code constant: '11' key. + // (0x000000e3) + int KEYCODE_11 = 227; + + // Key code constant: '12' key. + // (0x000000e4) + int KEYCODE_12 = 228; + + // Key code constant: '2' key. + // (0x00000009) + int KEYCODE_2 = 9; + + // Key code constant: '3' key. + // (0x0000000a) + int KEYCODE_3 = 10; + + // Key code constant: 3D Mode key. Toggles the display between 2D and 3D mode. + // (0x000000ce) + int KEYCODE_3D_MODE = 206; + + // Key code constant: '4' key. + // (0x0000000b) + int KEYCODE_4 = 11; + + // Key code constant: '5' key. + // (0x0000000c) + int KEYCODE_5 = 12; + + // Key code constant: '6' key. + // (0x0000000d) + int KEYCODE_6 = 13; - // Key code constant: '7' key. - // (0x0000000e) - int KEYCODE_7 = 14; + // Key code constant: '7' key. + // (0x0000000e) + int KEYCODE_7 = 14; - // Key code constant: '8' key. - // (0x0000000f) - int KEYCODE_8 = 15; + // Key code constant: '8' key. + // (0x0000000f) + int KEYCODE_8 = 15; - // Key code constant: '9' key. - // (0x00000010) - int KEYCODE_9 = 16; + // Key code constant: '9' key. + // (0x00000010) + int KEYCODE_9 = 16; - // Key code constant: 'A' key. - // (0x0000001d) - int KEYCODE_A = 29; + // Key code constant: 'A' key. + // (0x0000001d) + int KEYCODE_A = 29; - // Key code constant: Left Alt modifier key. - // (0x00000039) - int KEYCODE_ALT_LEFT = 57; + // Key code constant: Left Alt modifier key. + // (0x00000039) + int KEYCODE_ALT_LEFT = 57; - // Key code constant: Right Alt modifier key. - // (0x0000003a) - int KEYCODE_ALT_RIGHT = 58; + // Key code constant: Right Alt modifier key. + // (0x0000003a) + int KEYCODE_ALT_RIGHT = 58; - // Key code constant: ''' (apostrophe) key. - // (0x0000004b) - int KEYCODE_APOSTROPHE = 75; + // Key code constant: ''' (apostrophe) key. + // (0x0000004b) + int KEYCODE_APOSTROPHE = 75; - // Key code constant: App switch key. Should bring up the application switcher dialog. - // (0x000000bb) - int KEYCODE_APP_SWITCH = 187; + // Key code constant: App switch key. Should bring up the application switcher dialog. + // (0x000000bb) + int KEYCODE_APP_SWITCH = 187; - // Key code constant: Assist key. Launches the global assist activity. Not delivered to applications. - // (0x000000db) - int KEYCODE_ASSIST = 219; + // Key code constant: Assist key. Launches the global assist activity. Not delivered to applications. + // (0x000000db) + int KEYCODE_ASSIST = 219; - // Key code constant: '@' key. - // (0x0000004d) - int KEYCODE_AT = 77; + // Key code constant: '@' key. + // (0x0000004d) + int KEYCODE_AT = 77; - // Key code constant: A/V Receiver input key. On TV remotes, switches the input mode on an external A/V Receiver. - // (0x000000b6) - int KEYCODE_AVR_INPUT = 182; + // Key code constant: A/V Receiver input key. On TV remotes, switches the input mode on an external A/V Receiver. + // (0x000000b6) + int KEYCODE_AVR_INPUT = 182; - // Key code constant: A/V Receiver power key. On TV remotes, toggles the power on an external A/V Receiver. - // (0x000000b5) - int KEYCODE_AVR_POWER = 181; + // Key code constant: A/V Receiver power key. On TV remotes, toggles the power on an external A/V Receiver. + // (0x000000b5) + int KEYCODE_AVR_POWER = 181; - // Key code constant: 'B' key. - // (0x0000001e) - int KEYCODE_B = 30; + // Key code constant: 'B' key. + // (0x0000001e) + int KEYCODE_B = 30; - // Key code constant: Back key. - // (0x00000004) - int KEYCODE_BACK = 4; + // Key code constant: Back key. + // (0x00000004) + int KEYCODE_BACK = 4; - // Key code constant: '\' key. - // (0x00000049) - int KEYCODE_BACKSLASH = 73; + // Key code constant: '\' key. + // (0x00000049) + int KEYCODE_BACKSLASH = 73; - // Key code constant: Bookmark key. On some TV remotes, bookmarks content or web pages. - // (0x000000ae) - int KEYCODE_BOOKMARK = 174; + // Key code constant: Bookmark key. On some TV remotes, bookmarks content or web pages. + // (0x000000ae) + int KEYCODE_BOOKMARK = 174; - // Key code constant: Break / Pause key. - // (0x00000079) - int KEYCODE_BREAK = 121; + // Key code constant: Break / Pause key. + // (0x00000079) + int KEYCODE_BREAK = 121; - // Key code constant: Brightness Down key. Adjusts the screen brightness down. - // (0x000000dc) - int KEYCODE_BRIGHTNESS_DOWN = 220; + // Key code constant: Brightness Down key. Adjusts the screen brightness down. + // (0x000000dc) + int KEYCODE_BRIGHTNESS_DOWN = 220; - // Key code constant: Brightness Up key. Adjusts the screen brightness up. - // (0x000000dd) - int KEYCODE_BRIGHTNESS_UP = 221; + // Key code constant: Brightness Up key. Adjusts the screen brightness up. + // (0x000000dd) + int KEYCODE_BRIGHTNESS_UP = 221; - // Key code constant: Generic Game Pad Button #1. - // (0x000000bc) - int KEYCODE_BUTTON_1 = 188; + // Key code constant: Generic Game Pad Button #1. + // (0x000000bc) + int KEYCODE_BUTTON_1 = 188; - // Key code constant: Generic Game Pad Button #10. - // (0x000000c5) - int KEYCODE_BUTTON_10 = 197; + // Key code constant: Generic Game Pad Button #10. + // (0x000000c5) + int KEYCODE_BUTTON_10 = 197; - // Key code constant: Generic Game Pad Button #11. - // (0x000000c6) - int KEYCODE_BUTTON_11 = 198; + // Key code constant: Generic Game Pad Button #11. + // (0x000000c6) + int KEYCODE_BUTTON_11 = 198; - // Key code constant: Generic Game Pad Button #12. - // (0x000000c7) - int KEYCODE_BUTTON_12 = 199; + // Key code constant: Generic Game Pad Button #12. + // (0x000000c7) + int KEYCODE_BUTTON_12 = 199; - // Key code constant: Generic Game Pad Button #13. - // (0x000000c8) - int KEYCODE_BUTTON_13 = 200; + // Key code constant: Generic Game Pad Button #13. + // (0x000000c8) + int KEYCODE_BUTTON_13 = 200; - // Key code constant: Generic Game Pad Button #14. - // (0x000000c9) - int KEYCODE_BUTTON_14 = 201; + // Key code constant: Generic Game Pad Button #14. + // (0x000000c9) + int KEYCODE_BUTTON_14 = 201; - // Key code constant: Generic Game Pad Button #15. - // (0x000000ca) - int KEYCODE_BUTTON_15 = 202; + // Key code constant: Generic Game Pad Button #15. + // (0x000000ca) + int KEYCODE_BUTTON_15 = 202; - // Key code constant: Generic Game Pad Button #16. - // (0x000000cb) - int KEYCODE_BUTTON_16 = 203; + // Key code constant: Generic Game Pad Button #16. + // (0x000000cb) + int KEYCODE_BUTTON_16 = 203; - // Key code constant: Generic Game Pad Button #2. - // (0x000000bd) - int KEYCODE_BUTTON_2 = 189; + // Key code constant: Generic Game Pad Button #2. + // (0x000000bd) + int KEYCODE_BUTTON_2 = 189; - // Key code constant: Generic Game Pad Button #3. - // (0x000000be) - int KEYCODE_BUTTON_3 = 190; + // Key code constant: Generic Game Pad Button #3. + // (0x000000be) + int KEYCODE_BUTTON_3 = 190; - // Key code constant: Generic Game Pad Button #4. - // (0x000000bf) - int KEYCODE_BUTTON_4 = 191; + // Key code constant: Generic Game Pad Button #4. + // (0x000000bf) + int KEYCODE_BUTTON_4 = 191; - // Key code constant: Generic Game Pad Button #5. - // (0x000000c0) - int KEYCODE_BUTTON_5 = 192; + // Key code constant: Generic Game Pad Button #5. + // (0x000000c0) + int KEYCODE_BUTTON_5 = 192; - // Key code constant: Generic Game Pad Button #6. - // (0x000000c1) - int KEYCODE_BUTTON_6 = 193; + // Key code constant: Generic Game Pad Button #6. + // (0x000000c1) + int KEYCODE_BUTTON_6 = 193; - // Key code constant: Generic Game Pad Button #7. - // (0x000000c2) - int KEYCODE_BUTTON_7 = 194; + // Key code constant: Generic Game Pad Button #7. + // (0x000000c2) + int KEYCODE_BUTTON_7 = 194; - // Key code constant: Generic Game Pad Button #8. - // (0x000000c3) - int KEYCODE_BUTTON_8 = 195; + // Key code constant: Generic Game Pad Button #8. + // (0x000000c3) + int KEYCODE_BUTTON_8 = 195; - // Key code constant: Generic Game Pad Button #9. - // (0x000000c4) - int KEYCODE_BUTTON_9 = 196; + // Key code constant: Generic Game Pad Button #9. + // (0x000000c4) + int KEYCODE_BUTTON_9 = 196; - // Key code constant: A Button key. On a game controller, the A button should be either the button labeled A or the first button on the bottom row of controller buttons. - // (0x00000060) - int KEYCODE_BUTTON_A = 96; + // Key code constant: A Button key. On a game controller, the A button should be either the button labeled A or the first button on the bottom row of controller buttons. + // (0x00000060) + int KEYCODE_BUTTON_A = 96; - // Key code constant: B Button key. On a game controller, the B button should be either the button labeled B or the second button on the bottom row of controller buttons. - // (0x00000061) - int KEYCODE_BUTTON_B = 97; + // Key code constant: B Button key. On a game controller, the B button should be either the button labeled B or the second button on the bottom row of controller buttons. + // (0x00000061) + int KEYCODE_BUTTON_B = 97; - // Key code constant: C Button key. On a game controller, the C button should be either the button labeled C or the third button on the bottom row of controller buttons. - // (0x00000062) - int KEYCODE_BUTTON_C = 98; + // Key code constant: C Button key. On a game controller, the C button should be either the button labeled C or the third button on the bottom row of controller buttons. + // (0x00000062) + int KEYCODE_BUTTON_C = 98; - // Key code constant: L1 Button key. On a game controller, the L1 button should be either the button labeled L1 (or L) or the top left trigger button. - // (0x00000066) - int KEYCODE_BUTTON_L1 = 102; + // Key code constant: L1 Button key. On a game controller, the L1 button should be either the button labeled L1 (or L) or the top left trigger button. + // (0x00000066) + int KEYCODE_BUTTON_L1 = 102; - // Key code constant: L2 Button key. On a game controller, the L2 button should be either the button labeled L2 or the bottom left trigger button. - // (0x00000068) - int KEYCODE_BUTTON_L2 = 104; + // Key code constant: L2 Button key. On a game controller, the L2 button should be either the button labeled L2 or the bottom left trigger button. + // (0x00000068) + int KEYCODE_BUTTON_L2 = 104; - // Key code constant: Mode Button key. On a game controller, the button labeled Mode. - // (0x0000006e) - int KEYCODE_BUTTON_MODE = 110; + // Key code constant: Mode Button key. On a game controller, the button labeled Mode. + // (0x0000006e) + int KEYCODE_BUTTON_MODE = 110; - // Key code constant: R1 Button key. On a game controller, the R1 button should be either the button labeled R1 (or R) or the top right trigger button. - // (0x00000067) - int KEYCODE_BUTTON_R1 = 103; + // Key code constant: R1 Button key. On a game controller, the R1 button should be either the button labeled R1 (or R) or the top right trigger button. + // (0x00000067) + int KEYCODE_BUTTON_R1 = 103; - // Key code constant: R2 Button key. On a game controller, the R2 button should be either the button labeled R2 or the bottom right trigger button. - // (0x00000069) - int KEYCODE_BUTTON_R2 = 105; + // Key code constant: R2 Button key. On a game controller, the R2 button should be either the button labeled R2 or the bottom right trigger button. + // (0x00000069) + int KEYCODE_BUTTON_R2 = 105; - // Key code constant: Select Button key. On a game controller, the button labeled Select. - // (0x0000006d) - int KEYCODE_BUTTON_SELECT = 109; + // Key code constant: Select Button key. On a game controller, the button labeled Select. + // (0x0000006d) + int KEYCODE_BUTTON_SELECT = 109; - // Key code constant: Start Button key. On a game controller, the button labeled Start. - // (0x0000006c) - int KEYCODE_BUTTON_START = 108; + // Key code constant: Start Button key. On a game controller, the button labeled Start. + // (0x0000006c) + int KEYCODE_BUTTON_START = 108; - // Key code constant: Left Thumb Button key. On a game controller, the left thumb button indicates that the left (or only) joystick is pressed. - // (0x0000006a) - int KEYCODE_BUTTON_THUMBL = 106; + // Key code constant: Left Thumb Button key. On a game controller, the left thumb button indicates that the left (or only) joystick is pressed. + // (0x0000006a) + int KEYCODE_BUTTON_THUMBL = 106; - // Key code constant: Right Thumb Button key. On a game controller, the right thumb button indicates that the right joystick is pressed. - // (0x0000006b) - int KEYCODE_BUTTON_THUMBR = 107; + // Key code constant: Right Thumb Button key. On a game controller, the right thumb button indicates that the right joystick is pressed. + // (0x0000006b) + int KEYCODE_BUTTON_THUMBR = 107; - // Key code constant: X Button key. On a game controller, the X button should be either the button labeled X or the first button on the upper row of controller buttons. - // (0x00000063) - int KEYCODE_BUTTON_X = 99; + // Key code constant: X Button key. On a game controller, the X button should be either the button labeled X or the first button on the upper row of controller buttons. + // (0x00000063) + int KEYCODE_BUTTON_X = 99; - // Key code constant: Y Button key. On a game controller, the Y button should be either the button labeled Y or the second button on the upper row of controller buttons. - // (0x00000064) - int KEYCODE_BUTTON_Y = 100; + // Key code constant: Y Button key. On a game controller, the Y button should be either the button labeled Y or the second button on the upper row of controller buttons. + // (0x00000064) + int KEYCODE_BUTTON_Y = 100; - // Key code constant: Z Button key. On a game controller, the Z button should be either the button labeled Z or the third button on the upper row of controller buttons. - // (0x00000065) - int KEYCODE_BUTTON_Z = 101; + // Key code constant: Z Button key. On a game controller, the Z button should be either the button labeled Z or the third button on the upper row of controller buttons. + // (0x00000065) + int KEYCODE_BUTTON_Z = 101; - // Key code constant: 'C' key. - // (0x0000001f) - int KEYCODE_C = 31; + // Key code constant: 'C' key. + // (0x0000001f) + int KEYCODE_C = 31; - // Key code constant: Calculator special function key. Used to launch a calculator application. - // (0x000000d2) - int KEYCODE_CALCULATOR = 210; + // Key code constant: Calculator special function key. Used to launch a calculator application. + // (0x000000d2) + int KEYCODE_CALCULATOR = 210; - // Key code constant: Calendar special function key. Used to launch a calendar application. - // (0x000000d0) - int KEYCODE_CALENDAR = 208; + // Key code constant: Calendar special function key. Used to launch a calendar application. + // (0x000000d0) + int KEYCODE_CALENDAR = 208; - // Key code constant: Call key. - // (0x00000005) - int KEYCODE_CALL = 5; + // Key code constant: Call key. + // (0x00000005) + int KEYCODE_CALL = 5; - // Key code constant: Camera key. Used to launch a camera application or take pictures. - // (0x0000001b) - int KEYCODE_CAMERA = 27; + // Key code constant: Camera key. Used to launch a camera application or take pictures. + // (0x0000001b) + int KEYCODE_CAMERA = 27; - // Key code constant: Caps Lock key. - // (0x00000073) - int KEYCODE_CAPS_LOCK = 115; + // Key code constant: Caps Lock key. + // (0x00000073) + int KEYCODE_CAPS_LOCK = 115; - // Key code constant: Toggle captions key. Switches the mode for closed-captioning text, for example during television shows. - // (0x000000af) - int KEYCODE_CAPTIONS = 175; + // Key code constant: Toggle captions key. Switches the mode for closed-captioning text, for example during television shows. + // (0x000000af) + int KEYCODE_CAPTIONS = 175; - // Key code constant: Channel down key. On TV remotes, decrements the television channel. - // (0x000000a7) - int KEYCODE_CHANNEL_DOWN = 167; + // Key code constant: Channel down key. On TV remotes, decrements the television channel. + // (0x000000a7) + int KEYCODE_CHANNEL_DOWN = 167; - // Key code constant: Channel up key. On TV remotes, increments the television channel. - // (0x000000a6) - int KEYCODE_CHANNEL_UP = 166; + // Key code constant: Channel up key. On TV remotes, increments the television channel. + // (0x000000a6) + int KEYCODE_CHANNEL_UP = 166; - // Key code constant: Clear key. - // (0x0000001c) - int KEYCODE_CLEAR = 28; + // Key code constant: Clear key. + // (0x0000001c) + int KEYCODE_CLEAR = 28; - // Key code constant: ',' key. - // (0x00000037) - int KEYCODE_COMMA = 55; + // Key code constant: ',' key. + // (0x00000037) + int KEYCODE_COMMA = 55; - // Key code constant: Contacts special function key. Used to launch an address book application. - // (0x000000cf) - int KEYCODE_CONTACTS = 207; + // Key code constant: Contacts special function key. Used to launch an address book application. + // (0x000000cf) + int KEYCODE_CONTACTS = 207; - // Key code constant: Left Control modifier key. - // (0x00000071) - int KEYCODE_CTRL_LEFT = 113; + // Key code constant: Left Control modifier key. + // (0x00000071) + int KEYCODE_CTRL_LEFT = 113; - // Key code constant: Right Control modifier key. - // (0x00000072) - int KEYCODE_CTRL_RIGHT = 114; + // Key code constant: Right Control modifier key. + // (0x00000072) + int KEYCODE_CTRL_RIGHT = 114; - // Key code constant: 'D' key. - // (0x00000020) - int KEYCODE_D = 32; + // Key code constant: 'D' key. + // (0x00000020) + int KEYCODE_D = 32; - // Key code constant: Backspace key. Deletes characters before the insertion point, unlike KEYCODE_FORWARD_DEL. - // (0x00000043) - int KEYCODE_DEL = 67; + // Key code constant: Backspace key. Deletes characters before the insertion point, unlike KEYCODE_FORWARD_DEL. + // (0x00000043) + int KEYCODE_DEL = 67; - // Key code constant: Directional Pad Center key. May also be synthesized from trackball motions. - // (0x00000017) - int KEYCODE_DPAD_CENTER = 23; + // Key code constant: Directional Pad Center key. May also be synthesized from trackball motions. + // (0x00000017) + int KEYCODE_DPAD_CENTER = 23; - // Key code constant: Directional Pad Down key. May also be synthesized from trackball motions. - // (0x00000014) - int KEYCODE_DPAD_DOWN = 20; + // Key code constant: Directional Pad Down key. May also be synthesized from trackball motions. + // (0x00000014) + int KEYCODE_DPAD_DOWN = 20; - // Key code constant: Directional Pad Left key. May also be synthesized from trackball motions. - // (0x00000015) - int KEYCODE_DPAD_LEFT = 21; + // Key code constant: Directional Pad Left key. May also be synthesized from trackball motions. + // (0x00000015) + int KEYCODE_DPAD_LEFT = 21; - // Key code constant: Directional Pad Right key. May also be synthesized from trackball motions. - // (0x00000016) - int KEYCODE_DPAD_RIGHT = 22; + // Key code constant: Directional Pad Right key. May also be synthesized from trackball motions. + // (0x00000016) + int KEYCODE_DPAD_RIGHT = 22; - // Key code constant: Directional Pad Up key. May also be synthesized from trackball motions. - // (0x00000013) - int KEYCODE_DPAD_UP = 19; + // Key code constant: Directional Pad Up key. May also be synthesized from trackball motions. + // (0x00000013) + int KEYCODE_DPAD_UP = 19; - // Key code constant: DVR key. On some TV remotes, switches to a DVR mode for recorded shows. - // (0x000000ad) - int KEYCODE_DVR = 173; + // Key code constant: DVR key. On some TV remotes, switches to a DVR mode for recorded shows. + // (0x000000ad) + int KEYCODE_DVR = 173; - // Key code constant: 'E' key. - // (0x00000021) - int KEYCODE_E = 33; + // Key code constant: 'E' key. + // (0x00000021) + int KEYCODE_E = 33; - // Key code constant: Japanese alphanumeric key. - // (0x000000d4) - int KEYCODE_EISU = 212; + // Key code constant: Japanese alphanumeric key. + // (0x000000d4) + int KEYCODE_EISU = 212; - // Key code constant: End Call key. - // (0x00000006) - int KEYCODE_ENDCALL = 6; + // Key code constant: End Call key. + // (0x00000006) + int KEYCODE_ENDCALL = 6; - // Key code constant: Enter key. - // (0x00000042) - int KEYCODE_ENTER = 66; + // Key code constant: Enter key. + // (0x00000042) + int KEYCODE_ENTER = 66; - // Key code constant: Envelope special function key. Used to launch a mail application. - // (0x00000041) - int KEYCODE_ENVELOPE = 65; + // Key code constant: Envelope special function key. Used to launch a mail application. + // (0x00000041) + int KEYCODE_ENVELOPE = 65; - // Key code constant: '=' key. - // (0x00000046) - int KEYCODE_EQUALS = 70; + // Key code constant: '=' key. + // (0x00000046) + int KEYCODE_EQUALS = 70; - // Key code constant: Escape key. - // (0x0000006f) - int KEYCODE_ESCAPE = 111; + // Key code constant: Escape key. + // (0x0000006f) + int KEYCODE_ESCAPE = 111; - // Key code constant: Explorer special function key. Used to launch a browser application. - // (0x00000040) - int KEYCODE_EXPLORER = 64; + // Key code constant: Explorer special function key. Used to launch a browser application. + // (0x00000040) + int KEYCODE_EXPLORER = 64; - // Key code constant: 'F' key. - // (0x00000022) - int KEYCODE_F = 34; + // Key code constant: 'F' key. + // (0x00000022) + int KEYCODE_F = 34; - // Key code constant: F1 key. - // (0x00000083) - int KEYCODE_F1 = 131; + // Key code constant: F1 key. + // (0x00000083) + int KEYCODE_F1 = 131; - // Key code constant: F10 key. - // (0x0000008c) - int KEYCODE_F10 = 140; + // Key code constant: F10 key. + // (0x0000008c) + int KEYCODE_F10 = 140; - // Key code constant: F11 key. - // (0x0000008d) - int KEYCODE_F11 = 141; + // Key code constant: F11 key. + // (0x0000008d) + int KEYCODE_F11 = 141; - // Key code constant: F12 key. - // (0x0000008e) - int KEYCODE_F12 = 142; + // Key code constant: F12 key. + // (0x0000008e) + int KEYCODE_F12 = 142; - // Key code constant: F2 key. - // (0x00000084) - int KEYCODE_F2 = 132; + // Key code constant: F2 key. + // (0x00000084) + int KEYCODE_F2 = 132; - // Key code constant: F3 key. - // (0x00000085) - int KEYCODE_F3 = 133; + // Key code constant: F3 key. + // (0x00000085) + int KEYCODE_F3 = 133; - // Key code constant: F4 key. - // (0x00000086) - int KEYCODE_F4 = 134; + // Key code constant: F4 key. + // (0x00000086) + int KEYCODE_F4 = 134; - // Key code constant: F5 key. - // (0x00000087) - int KEYCODE_F5 = 135; + // Key code constant: F5 key. + // (0x00000087) + int KEYCODE_F5 = 135; - // Key code constant: F6 key. - // (0x00000088) - int KEYCODE_F6 = 136; + // Key code constant: F6 key. + // (0x00000088) + int KEYCODE_F6 = 136; - // Key code constant: F7 key. - // (0x00000089) - int KEYCODE_F7 = 137; + // Key code constant: F7 key. + // (0x00000089) + int KEYCODE_F7 = 137; - // Key code constant: F8 key. - // (0x0000008a) - int KEYCODE_F8 = 138; + // Key code constant: F8 key. + // (0x0000008a) + int KEYCODE_F8 = 138; - // Key code constant: F9 key. - // (0x0000008b) - int KEYCODE_F9 = 139; + // Key code constant: F9 key. + // (0x0000008b) + int KEYCODE_F9 = 139; - // Key code constant: Camera Focus key. Used to focus the camera. - // (0x00000050) - int KEYCODE_FOCUS = 80; + // Key code constant: Camera Focus key. Used to focus the camera. + // (0x00000050) + int KEYCODE_FOCUS = 80; - // Key code constant: Forward key. Navigates forward in the history stack. Complement of KEYCODE_BACK. - // (0x0000007d) - int KEYCODE_FORWARD = 125; + // Key code constant: Forward key. Navigates forward in the history stack. Complement of KEYCODE_BACK. + // (0x0000007d) + int KEYCODE_FORWARD = 125; - // Key code constant: Forward Delete key. Deletes characters ahead of the insertion point, unlike KEYCODE_DEL. - // (0x00000070) - int KEYCODE_FORWARD_DEL = 112; + // Key code constant: Forward Delete key. Deletes characters ahead of the insertion point, unlike KEYCODE_DEL. + // (0x00000070) + int KEYCODE_FORWARD_DEL = 112; - // Key code constant: Function modifier key. - // (0x00000077) - int KEYCODE_FUNCTION = 119; + // Key code constant: Function modifier key. + // (0x00000077) + int KEYCODE_FUNCTION = 119; - // Key code constant: 'G' key. - // (0x00000023) - int KEYCODE_G = 35; + // Key code constant: 'G' key. + // (0x00000023) + int KEYCODE_G = 35; - // Key code constant: '`' (backtick) key. - // (0x00000044) - int KEYCODE_GRAVE = 68; + // Key code constant: '`' (backtick) key. + // (0x00000044) + int KEYCODE_GRAVE = 68; - // Key code constant: Guide key. On TV remotes, shows a programming guide. - // (0x000000ac) - int KEYCODE_GUIDE = 172; + // Key code constant: Guide key. On TV remotes, shows a programming guide. + // (0x000000ac) + int KEYCODE_GUIDE = 172; - // Key code constant: 'H' key. - // (0x00000024) - int KEYCODE_H = 36; + // Key code constant: 'H' key. + // (0x00000024) + int KEYCODE_H = 36; - // Key code constant: Headset Hook key. Used to hang up calls and stop media. - // (0x0000004f) - int KEYCODE_HEADSETHOOK = 79; + // Key code constant: Headset Hook key. Used to hang up calls and stop media. + // (0x0000004f) + int KEYCODE_HEADSETHOOK = 79; - // Key code constant: Help key. - // (0x00000103) - int KEYCODE_HELP = 259; + // Key code constant: Help key. + // (0x00000103) + int KEYCODE_HELP = 259; - // Key code constant: Japanese conversion key. - // (0x000000d6) - int KEYCODE_HENKAN = 214; + // Key code constant: Japanese conversion key. + // (0x000000d6) + int KEYCODE_HENKAN = 214; - // Key code constant: Home key. This key is handled by the framework and is never delivered to applications. - // (0x00000003) - int KEYCODE_HOME = 3; + // Key code constant: Home key. This key is handled by the framework and is never delivered to applications. + // (0x00000003) + int KEYCODE_HOME = 3; - // Key code constant: 'I' key. - // (0x00000025) - int KEYCODE_I = 37; + // Key code constant: 'I' key. + // (0x00000025) + int KEYCODE_I = 37; - // Key code constant: Info key. Common on TV remotes to show additional information related to what is currently being viewed. - // (0x000000a5) - int KEYCODE_INFO = 165; + // Key code constant: Info key. Common on TV remotes to show additional information related to what is currently being viewed. + // (0x000000a5) + int KEYCODE_INFO = 165; - // Key code constant: Insert key. Toggles insert / overwrite edit mode. - // (0x0000007c) - int KEYCODE_INSERT = 124; + // Key code constant: Insert key. Toggles insert / overwrite edit mode. + // (0x0000007c) + int KEYCODE_INSERT = 124; - // Key code constant: 'J' key. - // (0x00000026) - int KEYCODE_J = 38; + // Key code constant: 'J' key. + // (0x00000026) + int KEYCODE_J = 38; - // Key code constant: 'K' key. - // (0x00000027) - int KEYCODE_K = 39; + // Key code constant: 'K' key. + // (0x00000027) + int KEYCODE_K = 39; - // Key code constant: Japanese kana key. - // (0x000000da) - int KEYCODE_KANA = 218; + // Key code constant: Japanese kana key. + // (0x000000da) + int KEYCODE_KANA = 218; - // Key code constant: Japanese katakana / hiragana key. - // (0x000000d7) - int KEYCODE_KATAKANA_HIRAGANA = 215; + // Key code constant: Japanese katakana / hiragana key. + // (0x000000d7) + int KEYCODE_KATAKANA_HIRAGANA = 215; - // Key code constant: 'L' key. - // (0x00000028) - int KEYCODE_L = 40; + // Key code constant: 'L' key. + // (0x00000028) + int KEYCODE_L = 40; - // Key code constant: Language Switch key. Toggles the current input language such as switching between English and Japanese on a QWERTY keyboard. On some devices, the same function may be performed by pressing Shift+Spacebar. - // (0x000000cc) - int KEYCODE_LANGUAGE_SWITCH = 204; + // Key code constant: Language Switch key. Toggles the current input language such as switching between English and Japanese on a QWERTY keyboard. On some devices, the same function may be performed by pressing Shift+Spacebar. + // (0x000000cc) + int KEYCODE_LANGUAGE_SWITCH = 204; - // Key code constant: Last Channel key. Goes to the last viewed channel. - // (0x000000e5) - int KEYCODE_LAST_CHANNEL = 229; + // Key code constant: Last Channel key. Goes to the last viewed channel. + // (0x000000e5) + int KEYCODE_LAST_CHANNEL = 229; - // Key code constant: '[' key. - // (0x00000047) - int KEYCODE_LEFT_BRACKET = 71; + // Key code constant: '[' key. + // (0x00000047) + int KEYCODE_LEFT_BRACKET = 71; - // Key code constant: 'M' key. - // (0x00000029) - int KEYCODE_M = 41; + // Key code constant: 'M' key. + // (0x00000029) + int KEYCODE_M = 41; - // Key code constant: Manner Mode key. Toggles silent or vibrate mode on and off to make the device behave more politely in certain settings such as on a crowded train. On some devices, the key may only operate when long-pressed. - // (0x000000cd) - int KEYCODE_MANNER_MODE = 205; + // Key code constant: Manner Mode key. Toggles silent or vibrate mode on and off to make the device behave more politely in certain settings such as on a crowded train. On some devices, the key may only operate when long-pressed. + // (0x000000cd) + int KEYCODE_MANNER_MODE = 205; - // Key code constant: Audio Track key. Switches the audio tracks. - // (0x000000de) - int KEYCODE_MEDIA_AUDIO_TRACK = 222; + // Key code constant: Audio Track key. Switches the audio tracks. + // (0x000000de) + int KEYCODE_MEDIA_AUDIO_TRACK = 222; - // Key code constant: Close media key. May be used to close a CD tray, for example. - // (0x00000080) - int KEYCODE_MEDIA_CLOSE = 128; + // Key code constant: Close media key. May be used to close a CD tray, for example. + // (0x00000080) + int KEYCODE_MEDIA_CLOSE = 128; - // Key code constant: Eject media key. May be used to eject a CD tray, for example. - // (0x00000081) - int KEYCODE_MEDIA_EJECT = 129; + // Key code constant: Eject media key. May be used to eject a CD tray, for example. + // (0x00000081) + int KEYCODE_MEDIA_EJECT = 129; - // Key code constant: Fast Forward media key. - // (0x0000005a) - int KEYCODE_MEDIA_FAST_FORWARD = 90; + // Key code constant: Fast Forward media key. + // (0x0000005a) + int KEYCODE_MEDIA_FAST_FORWARD = 90; - // Key code constant: Play Next media key. - // (0x00000057) - int KEYCODE_MEDIA_NEXT = 87; + // Key code constant: Play Next media key. + // (0x00000057) + int KEYCODE_MEDIA_NEXT = 87; - // Key code constant: Pause media key. - // (0x0000007f) - int KEYCODE_MEDIA_PAUSE = 127; + // Key code constant: Pause media key. + // (0x0000007f) + int KEYCODE_MEDIA_PAUSE = 127; - // Key code constant: Play media key. - // (0x0000007e) - int KEYCODE_MEDIA_PLAY = 126; + // Key code constant: Play media key. + // (0x0000007e) + int KEYCODE_MEDIA_PLAY = 126; - // Key code constant: Play/Pause media key. - // (0x00000055) - int KEYCODE_MEDIA_PLAY_PAUSE = 85; + // Key code constant: Play/Pause media key. + // (0x00000055) + int KEYCODE_MEDIA_PLAY_PAUSE = 85; - // Key code constant: Play Previous media key. - // (0x00000058) - int KEYCODE_MEDIA_PREVIOUS = 88; + // Key code constant: Play Previous media key. + // (0x00000058) + int KEYCODE_MEDIA_PREVIOUS = 88; - // Key code constant: Record media key. - // (0x00000082) - int KEYCODE_MEDIA_RECORD = 130; + // Key code constant: Record media key. + // (0x00000082) + int KEYCODE_MEDIA_RECORD = 130; - // Key code constant: Rewind media key. - // (0x00000059) - int KEYCODE_MEDIA_REWIND = 89; + // Key code constant: Rewind media key. + // (0x00000059) + int KEYCODE_MEDIA_REWIND = 89; - // Key code constant: Stop media key. - // (0x00000056) - int KEYCODE_MEDIA_STOP = 86; + // Key code constant: Stop media key. + // (0x00000056) + int KEYCODE_MEDIA_STOP = 86; - // Key code constant: Media Top Menu key. Goes to the top of media menu. - // (0x000000e2) - int KEYCODE_MEDIA_TOP_MENU = 226; + // Key code constant: Media Top Menu key. Goes to the top of media menu. + // (0x000000e2) + int KEYCODE_MEDIA_TOP_MENU = 226; - // Key code constant: Menu key. - // (0x00000052) - int KEYCODE_MENU = 82; + // Key code constant: Menu key. + // (0x00000052) + int KEYCODE_MENU = 82; - // Key code constant: Left Meta modifier key. - // (0x00000075) - int KEYCODE_META_LEFT = 117; + // Key code constant: Left Meta modifier key. + // (0x00000075) + int KEYCODE_META_LEFT = 117; - // Key code constant: Right Meta modifier key. - // (0x00000076) - int KEYCODE_META_RIGHT = 118; + // Key code constant: Right Meta modifier key. + // (0x00000076) + int KEYCODE_META_RIGHT = 118; - // Key code constant: '-'. - // (0x00000045) - int KEYCODE_MINUS = 69; + // Key code constant: '-'. + // (0x00000045) + int KEYCODE_MINUS = 69; - // Key code constant: End Movement key. Used for scrolling or moving the cursor around to the end of a line or to the bottom of a list. - // (0x0000007b) - int KEYCODE_MOVE_END = 123; + // Key code constant: End Movement key. Used for scrolling or moving the cursor around to the end of a line or to the bottom of a list. + // (0x0000007b) + int KEYCODE_MOVE_END = 123; - // Key code constant: Home Movement key. Used for scrolling or moving the cursor around to the start of a line or to the top of a list. - // (0x0000007a) - int KEYCODE_MOVE_HOME = 122; + // Key code constant: Home Movement key. Used for scrolling or moving the cursor around to the start of a line or to the top of a list. + // (0x0000007a) + int KEYCODE_MOVE_HOME = 122; - // Key code constant: Japanese non-conversion key. - // (0x000000d5) - int KEYCODE_MUHENKAN = 213; + // Key code constant: Japanese non-conversion key. + // (0x000000d5) + int KEYCODE_MUHENKAN = 213; - // Key code constant: Music special function key. Used to launch a music player application. - // (0x000000d1) - int KEYCODE_MUSIC = 209; + // Key code constant: Music special function key. Used to launch a music player application. + // (0x000000d1) + int KEYCODE_MUSIC = 209; - // Key code constant: Mute key. Mutes the microphone, unlike KEYCODE_VOLUME_MUTE. - // (0x0000005b) - int KEYCODE_MUTE = 91; + // Key code constant: Mute key. Mutes the microphone, unlike KEYCODE_VOLUME_MUTE. + // (0x0000005b) + int KEYCODE_MUTE = 91; - // Key code constant: 'N' key. - // (0x0000002a) - int KEYCODE_N = 42; + // Key code constant: 'N' key. + // (0x0000002a) + int KEYCODE_N = 42; - // Key code constant: Notification key. - // (0x00000053) - int KEYCODE_NOTIFICATION = 83; + // Key code constant: Notification key. + // (0x00000053) + int KEYCODE_NOTIFICATION = 83; - // Key code constant: Number modifier key. Used to enter numeric symbols. This key is not Num Lock; it is more like KEYCODE_ALT_LEFT and is interpreted as an ALT key by MetaKeyKeyListener. - // (0x0000004e) - int KEYCODE_NUM = 78; + // Key code constant: Number modifier key. Used to enter numeric symbols. This key is not Num Lock; it is more like KEYCODE_ALT_LEFT and is interpreted as an ALT key by MetaKeyKeyListener. + // (0x0000004e) + int KEYCODE_NUM = 78; - // Key code constant: Numeric keypad '0' key. - // (0x00000090) - int KEYCODE_NUMPAD_0 = 144; + // Key code constant: Numeric keypad '0' key. + // (0x00000090) + int KEYCODE_NUMPAD_0 = 144; - // Key code constant: Numeric keypad '1' key. - // (0x00000091) - int KEYCODE_NUMPAD_1 = 145; + // Key code constant: Numeric keypad '1' key. + // (0x00000091) + int KEYCODE_NUMPAD_1 = 145; - // Key code constant: Numeric keypad '2' key. - // (0x00000092) - int KEYCODE_NUMPAD_2 = 146; + // Key code constant: Numeric keypad '2' key. + // (0x00000092) + int KEYCODE_NUMPAD_2 = 146; - // Key code constant: Numeric keypad '3' key. - // (0x00000093) - int KEYCODE_NUMPAD_3 = 147; + // Key code constant: Numeric keypad '3' key. + // (0x00000093) + int KEYCODE_NUMPAD_3 = 147; - // Key code constant: Numeric keypad '4' key. - // (0x00000094) - int KEYCODE_NUMPAD_4 = 148; + // Key code constant: Numeric keypad '4' key. + // (0x00000094) + int KEYCODE_NUMPAD_4 = 148; - // Key code constant: Numeric keypad '5' key. - // (0x00000095) - int KEYCODE_NUMPAD_5 = 149; + // Key code constant: Numeric keypad '5' key. + // (0x00000095) + int KEYCODE_NUMPAD_5 = 149; - // Key code constant: Numeric keypad '6' key. - // (0x00000096) - int KEYCODE_NUMPAD_6 = 150; + // Key code constant: Numeric keypad '6' key. + // (0x00000096) + int KEYCODE_NUMPAD_6 = 150; - // Key code constant: Numeric keypad '7' key. - // (0x00000097) - int KEYCODE_NUMPAD_7 = 151; + // Key code constant: Numeric keypad '7' key. + // (0x00000097) + int KEYCODE_NUMPAD_7 = 151; - // Key code constant: Numeric keypad '8' key. - // (0x00000098) - int KEYCODE_NUMPAD_8 = 152; + // Key code constant: Numeric keypad '8' key. + // (0x00000098) + int KEYCODE_NUMPAD_8 = 152; - // Key code constant: Numeric keypad '9' key. - // (0x00000099) - int KEYCODE_NUMPAD_9 = 153; + // Key code constant: Numeric keypad '9' key. + // (0x00000099) + int KEYCODE_NUMPAD_9 = 153; - // Key code constant: Numeric keypad '+' key (for addition). - // (0x0000009d) - int KEYCODE_NUMPAD_ADD = 157; + // Key code constant: Numeric keypad '+' key (for addition). + // (0x0000009d) + int KEYCODE_NUMPAD_ADD = 157; - // Key code constant: Numeric keypad ',' key (for decimals or digit grouping). - // (0x0000009f) - int KEYCODE_NUMPAD_COMMA = 159; + // Key code constant: Numeric keypad ',' key (for decimals or digit grouping). + // (0x0000009f) + int KEYCODE_NUMPAD_COMMA = 159; - // Key code constant: Numeric keypad '/' key (for division). - // (0x0000009a) - int KEYCODE_NUMPAD_DIVIDE = 154; + // Key code constant: Numeric keypad '/' key (for division). + // (0x0000009a) + int KEYCODE_NUMPAD_DIVIDE = 154; - // Key code constant: Numeric keypad '.' key (for decimals or digit grouping). - // (0x0000009e) - int KEYCODE_NUMPAD_DOT = 158; + // Key code constant: Numeric keypad '.' key (for decimals or digit grouping). + // (0x0000009e) + int KEYCODE_NUMPAD_DOT = 158; - // Key code constant: Numeric keypad Enter key. - // (0x000000a0) - int KEYCODE_NUMPAD_ENTER = 160; + // Key code constant: Numeric keypad Enter key. + // (0x000000a0) + int KEYCODE_NUMPAD_ENTER = 160; - // Key code constant: Numeric keypad '=' key. - // (0x000000a1) - int KEYCODE_NUMPAD_EQUALS = 161; + // Key code constant: Numeric keypad '=' key. + // (0x000000a1) + int KEYCODE_NUMPAD_EQUALS = 161; - // Key code constant: Numeric keypad '(' key. - // (0x000000a2) - int KEYCODE_NUMPAD_LEFT_PAREN = 162; + // Key code constant: Numeric keypad '(' key. + // (0x000000a2) + int KEYCODE_NUMPAD_LEFT_PAREN = 162; - // Key code constant: Numeric keypad '*' key (for multiplication). - // (0x0000009b) - int KEYCODE_NUMPAD_MULTIPLY = 155; + // Key code constant: Numeric keypad '*' key (for multiplication). + // (0x0000009b) + int KEYCODE_NUMPAD_MULTIPLY = 155; - // Key code constant: Numeric keypad ')' key. - // (0x000000a3) - int KEYCODE_NUMPAD_RIGHT_PAREN = 163; + // Key code constant: Numeric keypad ')' key. + // (0x000000a3) + int KEYCODE_NUMPAD_RIGHT_PAREN = 163; - // Key code constant: Numeric keypad '-' key (for subtraction). - // (0x0000009c) - int KEYCODE_NUMPAD_SUBTRACT = 156; + // Key code constant: Numeric keypad '-' key (for subtraction). + // (0x0000009c) + int KEYCODE_NUMPAD_SUBTRACT = 156; - // Key code constant: Num Lock key. This is the Num Lock key; it is different from KEYCODE_NUM. This key alters the behavior of other keys on the numeric keypad. - // (0x0000008f) - int KEYCODE_NUM_LOCK = 143; + // Key code constant: Num Lock key. This is the Num Lock key; it is different from KEYCODE_NUM. This key alters the behavior of other keys on the numeric keypad. + // (0x0000008f) + int KEYCODE_NUM_LOCK = 143; - // Key code constant: 'O' key. - // (0x0000002b) - int KEYCODE_O = 43; + // Key code constant: 'O' key. + // (0x0000002b) + int KEYCODE_O = 43; - // Key code constant: 'P' key. - // (0x0000002c) - int KEYCODE_P = 44; + // Key code constant: 'P' key. + // (0x0000002c) + int KEYCODE_P = 44; - // Key code constant: Page Down key. - // (0x0000005d) - int KEYCODE_PAGE_DOWN = 93; + // Key code constant: Page Down key. + // (0x0000005d) + int KEYCODE_PAGE_DOWN = 93; - // Key code constant: Page Up key. - // (0x0000005c) - int KEYCODE_PAGE_UP = 92; + // Key code constant: Page Up key. + // (0x0000005c) + int KEYCODE_PAGE_UP = 92; - // Key code constant: Pairing key. Initiates peripheral pairing mode. Useful for pairing remote control devices or game controllers, especially if no other input mode is available. - // (0x000000e1) - int KEYCODE_PAIRING = 225; + // Key code constant: Pairing key. Initiates peripheral pairing mode. Useful for pairing remote control devices or game controllers, especially if no other input mode is available. + // (0x000000e1) + int KEYCODE_PAIRING = 225; - // Key code constant: '.' key. - // (0x00000038) - int KEYCODE_PERIOD = 56; + // Key code constant: '.' key. + // (0x00000038) + int KEYCODE_PERIOD = 56; - // Key code constant: Picture Symbols modifier key. Used to switch symbol sets (Emoji, Kao-moji). - // (0x0000005e) - int KEYCODE_PICTSYMBOLS = 94; + // Key code constant: Picture Symbols modifier key. Used to switch symbol sets (Emoji, Kao-moji). + // (0x0000005e) + int KEYCODE_PICTSYMBOLS = 94; - // Key code constant: '+' key. - // (0x00000051) - int KEYCODE_PLUS = 81; + // Key code constant: '+' key. + // (0x00000051) + int KEYCODE_PLUS = 81; - // Key code constant: '#' key. - // (0x00000012) - int KEYCODE_POUND = 18; + // Key code constant: '#' key. + // (0x00000012) + int KEYCODE_POUND = 18; - // Key code constant: Power key. - // (0x0000001a) - int KEYCODE_POWER = 26; + // Key code constant: Power key. + // (0x0000001a) + int KEYCODE_POWER = 26; - // Key code constant: Blue "programmable" key. On TV remotes, acts as a contextual/programmable key. - // (0x000000ba) - int KEYCODE_PROG_BLUE = 186; + // Key code constant: Blue "programmable" key. On TV remotes, acts as a contextual/programmable key. + // (0x000000ba) + int KEYCODE_PROG_BLUE = 186; - // Key code constant: Green "programmable" key. On TV remotes, actsas a contextual/programmable key. - // (0x000000b8) - int KEYCODE_PROG_GREEN = 184; + // Key code constant: Green "programmable" key. On TV remotes, actsas a contextual/programmable key. + // (0x000000b8) + int KEYCODE_PROG_GREEN = 184; - // Key code constant: Red "programmable" key. On TV remotes, acts as a contextual/programmable key. - // (0x000000b7) - int KEYCODE_PROG_RED = 183; + // Key code constant: Red "programmable" key. On TV remotes, acts as a contextual/programmable key. + // (0x000000b7) + int KEYCODE_PROG_RED = 183; - // Key code constant: Yellow "programmable" key. On TV remotes, acts as a contextual/programmable key. - // (0x000000b9) - int KEYCODE_PROG_YELLOW = 185; + // Key code constant: Yellow "programmable" key. On TV remotes, acts as a contextual/programmable key. + // (0x000000b9) + int KEYCODE_PROG_YELLOW = 185; - // Key code constant: 'Q' key. - // (0x0000002d) - int KEYCODE_Q = 45; + // Key code constant: 'Q' key. + // (0x0000002d) + int KEYCODE_Q = 45; - // Key code constant: 'R' key. - // (0x0000002e) - int KEYCODE_R = 46; + // Key code constant: 'R' key. + // (0x0000002e) + int KEYCODE_R = 46; - // Key code constant: ']' key. - // (0x00000048) - int KEYCODE_RIGHT_BRACKET = 72; + // Key code constant: ']' key. + // (0x00000048) + int KEYCODE_RIGHT_BRACKET = 72; - // Key code constant: Japanese Ro key. - // (0x000000d9) - int KEYCODE_RO = 217; + // Key code constant: Japanese Ro key. + // (0x000000d9) + int KEYCODE_RO = 217; - // Key code constant: 'S' key. - // (0x0000002f) - int KEYCODE_S = 47; + // Key code constant: 'S' key. + // (0x0000002f) + int KEYCODE_S = 47; - // Key code constant: Scroll Lock key. - // (0x00000074) - int KEYCODE_SCROLL_LOCK = 116; + // Key code constant: Scroll Lock key. + // (0x00000074) + int KEYCODE_SCROLL_LOCK = 116; - // Key code constant: Search key. - // (0x00000054) - int KEYCODE_SEARCH = 84; + // Key code constant: Search key. + // (0x00000054) + int KEYCODE_SEARCH = 84; - // Key code constant: ';' key. - // (0x0000004a) - int KEYCODE_SEMICOLON = 74; + // Key code constant: ';' key. + // (0x0000004a) + int KEYCODE_SEMICOLON = 74; - // Key code constant: Settings key. Starts the system settings activity. - // (0x000000b0) - int KEYCODE_SETTINGS = 176; + // Key code constant: Settings key. Starts the system settings activity. + // (0x000000b0) + int KEYCODE_SETTINGS = 176; - // Key code constant: Left Shift modifier key. - // (0x0000003b) - int KEYCODE_SHIFT_LEFT = 59; + // Key code constant: Left Shift modifier key. + // (0x0000003b) + int KEYCODE_SHIFT_LEFT = 59; - // Key code constant: Right Shift modifier key. - // (0x0000003c) - int KEYCODE_SHIFT_RIGHT = 60; + // Key code constant: Right Shift modifier key. + // (0x0000003c) + int KEYCODE_SHIFT_RIGHT = 60; - // Key code constant: '/' key. - // (0x0000004c) - int KEYCODE_SLASH = 76; + // Key code constant: '/' key. + // (0x0000004c) + int KEYCODE_SLASH = 76; - // Key code constant: Sleep key. Puts the device to sleep. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already asleep. - // (0x000000df) - int KEYCODE_SLEEP = 223; + // Key code constant: Sleep key. Puts the device to sleep. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already asleep. + // (0x000000df) + int KEYCODE_SLEEP = 223; - // Key code constant: Soft Left key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom left of the display. - // (0x00000001) - int KEYCODE_SOFT_LEFT = 1; + // Key code constant: Soft Left key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom left of the display. + // (0x00000001) + int KEYCODE_SOFT_LEFT = 1; - // Key code constant: Soft Right key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom right of the display. - // (0x00000002) - int KEYCODE_SOFT_RIGHT = 2; + // Key code constant: Soft Right key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom right of the display. + // (0x00000002) + int KEYCODE_SOFT_RIGHT = 2; - // Key code constant: Space key. - // (0x0000003e) - int KEYCODE_SPACE = 62; + // Key code constant: Space key. + // (0x0000003e) + int KEYCODE_SPACE = 62; - // Key code constant: '*' key. - // (0x00000011) - int KEYCODE_STAR = 17; + // Key code constant: '*' key. + // (0x00000011) + int KEYCODE_STAR = 17; - // Key code constant: Set-top-box input key. On TV remotes, switches the input mode on an external Set-top-box. - // (0x000000b4) - int KEYCODE_STB_INPUT = 180; + // Key code constant: Set-top-box input key. On TV remotes, switches the input mode on an external Set-top-box. + // (0x000000b4) + int KEYCODE_STB_INPUT = 180; - // Key code constant: Set-top-box power key. On TV remotes, toggles the power on an external Set-top-box. - // (0x000000b3) - int KEYCODE_STB_POWER = 179; + // Key code constant: Set-top-box power key. On TV remotes, toggles the power on an external Set-top-box. + // (0x000000b3) + int KEYCODE_STB_POWER = 179; - // Key code constant: Switch Charset modifier key. Used to switch character sets (Kanji, Katakana). - // (0x0000005f) - int KEYCODE_SWITCH_CHARSET = 95; + // Key code constant: Switch Charset modifier key. Used to switch character sets (Kanji, Katakana). + // (0x0000005f) + int KEYCODE_SWITCH_CHARSET = 95; - // Key code constant: Symbol modifier key. Used to enter alternate symbols. - // (0x0000003f) - int KEYCODE_SYM = 63; + // Key code constant: Symbol modifier key. Used to enter alternate symbols. + // (0x0000003f) + int KEYCODE_SYM = 63; - // Key code constant: System Request / Print Screen key. - // (0x00000078) - int KEYCODE_SYSRQ = 120; + // Key code constant: System Request / Print Screen key. + // (0x00000078) + int KEYCODE_SYSRQ = 120; - // Key code constant: 'T' key. - // (0x00000030) - int KEYCODE_T = 48; + // Key code constant: 'T' key. + // (0x00000030) + int KEYCODE_T = 48; - // Key code constant: Tab key. - // (0x0000003d) - int KEYCODE_TAB = 61; + // Key code constant: Tab key. + // (0x0000003d) + int KEYCODE_TAB = 61; - // Key code constant: TV key. On TV remotes, switches to viewing live TV. - // (0x000000aa) - int KEYCODE_TV = 170; + // Key code constant: TV key. On TV remotes, switches to viewing live TV. + // (0x000000aa) + int KEYCODE_TV = 170; - // Key code constant: Antenna/Cable key. Toggles broadcast input source between antenna and cable. - // (0x000000f2) - int KEYCODE_TV_ANTENNA_CABLE = 242; + // Key code constant: Antenna/Cable key. Toggles broadcast input source between antenna and cable. + // (0x000000f2) + int KEYCODE_TV_ANTENNA_CABLE = 242; - // Key code constant: Audio description key. Toggles audio description off / on. - // (0x000000fc) - int KEYCODE_TV_AUDIO_DESCRIPTION = 252; + // Key code constant: Audio description key. Toggles audio description off / on. + // (0x000000fc) + int KEYCODE_TV_AUDIO_DESCRIPTION = 252; - // Key code constant: Audio description mixing volume down key. Lessen audio description volume as compared with normal audio volume. - // (0x000000fe) - int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254; + // Key code constant: Audio description mixing volume down key. Lessen audio description volume as compared with normal audio volume. + // (0x000000fe) + int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254; - // Key code constant: Audio description mixing volume up key. Louden audio description volume as compared with normal audio volume. - // (0x000000fd) - int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253; + // Key code constant: Audio description mixing volume up key. Louden audio description volume as compared with normal audio volume. + // (0x000000fd) + int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253; - // Key code constant: Contents menu key. Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control Code - // (0x00000100) - int KEYCODE_TV_CONTENTS_MENU = 256; + // Key code constant: Contents menu key. Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control Code + // (0x00000100) + int KEYCODE_TV_CONTENTS_MENU = 256; - // Key code constant: TV data service key. Displays data services like weather, sports. - // (0x000000e6) - int KEYCODE_TV_DATA_SERVICE = 230; + // Key code constant: TV data service key. Displays data services like weather, sports. + // (0x000000e6) + int KEYCODE_TV_DATA_SERVICE = 230; - // Key code constant: TV input key. On TV remotes, switches the input on a television screen. - // (0x000000b2) - int KEYCODE_TV_INPUT = 178; + // Key code constant: TV input key. On TV remotes, switches the input on a television screen. + // (0x000000b2) + int KEYCODE_TV_INPUT = 178; - // Key code constant: Component #1 key. Switches to component video input #1. - // (0x000000f9) - int KEYCODE_TV_INPUT_COMPONENT_1 = 249; + // Key code constant: Component #1 key. Switches to component video input #1. + // (0x000000f9) + int KEYCODE_TV_INPUT_COMPONENT_1 = 249; - // Key code constant: Component #2 key. Switches to component video input #2. - // (0x000000fa) - int KEYCODE_TV_INPUT_COMPONENT_2 = 250; + // Key code constant: Component #2 key. Switches to component video input #2. + // (0x000000fa) + int KEYCODE_TV_INPUT_COMPONENT_2 = 250; - // Key code constant: Composite #1 key. Switches to composite video input #1. - // (0x000000f7) - int KEYCODE_TV_INPUT_COMPOSITE_1 = 247; + // Key code constant: Composite #1 key. Switches to composite video input #1. + // (0x000000f7) + int KEYCODE_TV_INPUT_COMPOSITE_1 = 247; - // Key code constant: Composite #2 key. Switches to composite video input #2. - // (0x000000f8) - int KEYCODE_TV_INPUT_COMPOSITE_2 = 248; + // Key code constant: Composite #2 key. Switches to composite video input #2. + // (0x000000f8) + int KEYCODE_TV_INPUT_COMPOSITE_2 = 248; - // Key code constant: HDMI #1 key. Switches to HDMI input #1. - // (0x000000f3) - int KEYCODE_TV_INPUT_HDMI_1 = 243; + // Key code constant: HDMI #1 key. Switches to HDMI input #1. + // (0x000000f3) + int KEYCODE_TV_INPUT_HDMI_1 = 243; - // Key code constant: HDMI #2 key. Switches to HDMI input #2. - // (0x000000f4) - int KEYCODE_TV_INPUT_HDMI_2 = 244; + // Key code constant: HDMI #2 key. Switches to HDMI input #2. + // (0x000000f4) + int KEYCODE_TV_INPUT_HDMI_2 = 244; - // Key code constant: HDMI #3 key. Switches to HDMI input #3. - // (0x000000f5) - int KEYCODE_TV_INPUT_HDMI_3 = 245; + // Key code constant: HDMI #3 key. Switches to HDMI input #3. + // (0x000000f5) + int KEYCODE_TV_INPUT_HDMI_3 = 245; - // Key code constant: HDMI #4 key. Switches to HDMI input #4. - // (0x000000f6) - int KEYCODE_TV_INPUT_HDMI_4 = 246; + // Key code constant: HDMI #4 key. Switches to HDMI input #4. + // (0x000000f6) + int KEYCODE_TV_INPUT_HDMI_4 = 246; - // Key code constant: VGA #1 key. Switches to VGA (analog RGB) input #1. - // (0x000000fb) - int KEYCODE_TV_INPUT_VGA_1 = 251; + // Key code constant: VGA #1 key. Switches to VGA (analog RGB) input #1. + // (0x000000fb) + int KEYCODE_TV_INPUT_VGA_1 = 251; - // Key code constant: Media context menu key. Goes to the context menu of media contents. Corresponds to Media Context-sensitive Menu (0x11) of CEC User Control Code. - // (0x00000101) - int KEYCODE_TV_MEDIA_CONTEXT_MENU = 257; + // Key code constant: Media context menu key. Goes to the context menu of media contents. Corresponds to Media Context-sensitive Menu (0x11) of CEC User Control Code. + // (0x00000101) + int KEYCODE_TV_MEDIA_CONTEXT_MENU = 257; - // Key code constant: Toggle Network key. Toggles selecting broacast services. - // (0x000000f1) - int KEYCODE_TV_NETWORK = 241; + // Key code constant: Toggle Network key. Toggles selecting broacast services. + // (0x000000f1) + int KEYCODE_TV_NETWORK = 241; - // Key code constant: Number entry key. Initiates to enter multi-digit channel nubmber when each digit key is assigned for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC User Control Code. - // (0x000000ea) - int KEYCODE_TV_NUMBER_ENTRY = 234; + // Key code constant: Number entry key. Initiates to enter multi-digit channel nubmber when each digit key is assigned for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC User Control Code. + // (0x000000ea) + int KEYCODE_TV_NUMBER_ENTRY = 234; - // Key code constant: TV power key. On TV remotes, toggles the power on a television screen. - // (0x000000b1) - int KEYCODE_TV_POWER = 177; + // Key code constant: TV power key. On TV remotes, toggles the power on a television screen. + // (0x000000b1) + int KEYCODE_TV_POWER = 177; - // Key code constant: Radio key. Toggles TV service / Radio service. - // (0x000000e8) - int KEYCODE_TV_RADIO_SERVICE = 232; + // Key code constant: Radio key. Toggles TV service / Radio service. + // (0x000000e8) + int KEYCODE_TV_RADIO_SERVICE = 232; - // Key code constant: Satellite key. Switches to digital satellite broadcast service. - // (0x000000ed) - int KEYCODE_TV_SATELLITE = 237; + // Key code constant: Satellite key. Switches to digital satellite broadcast service. + // (0x000000ed) + int KEYCODE_TV_SATELLITE = 237; - // Key code constant: BS key. Switches to BS digital satellite broadcasting service available in Japan. - // (0x000000ee) - int KEYCODE_TV_SATELLITE_BS = 238; + // Key code constant: BS key. Switches to BS digital satellite broadcasting service available in Japan. + // (0x000000ee) + int KEYCODE_TV_SATELLITE_BS = 238; - // Key code constant: CS key. Switches to CS digital satellite broadcasting service available in Japan. - // (0x000000ef) - int KEYCODE_TV_SATELLITE_CS = 239; + // Key code constant: CS key. Switches to CS digital satellite broadcasting service available in Japan. + // (0x000000ef) + int KEYCODE_TV_SATELLITE_CS = 239; - // Key code constant: BS/CS key. Toggles between BS and CS digital satellite services. - // (0x000000f0) - int KEYCODE_TV_SATELLITE_SERVICE = 240; - - // Key code constant: Teletext key. Displays Teletext service. - // (0x000000e9) - int KEYCODE_TV_TELETEXT = 233; - - // Key code constant: Analog Terrestrial key. Switches to analog terrestrial broadcast service. - // (0x000000eb) - int KEYCODE_TV_TERRESTRIAL_ANALOG = 235; - - // Key code constant: Digital Terrestrial key. Switches to digital terrestrial broadcast service. - // (0x000000ec) - int KEYCODE_TV_TERRESTRIAL_DIGITAL = 236; - - // Key code constant: Timer programming key. Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of CEC User Control Code. - // (0x00000102) - int KEYCODE_TV_TIMER_PROGRAMMING = 258; - - // Key code constant: Zoom mode key. Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) - // (0x000000ff) - int KEYCODE_TV_ZOOM_MODE = 255; - - // Key code constant: 'U' key. - // (0x00000031) - int KEYCODE_U = 49; - - // Key code constant: Unknown key code. - // (0x00000000) - int KEYCODE_UNKNOWN = 0; - - // Key code constant: 'V' key. - // (0x00000032) - int KEYCODE_V = 50; - - // Key code constant: Voice Assist key. Launches the global voice assist activity. Not delivered to applications. - // (0x000000e7) - int KEYCODE_VOICE_ASSIST = 231; - - // Key code constant: Volume Down key. Adjusts the speaker volume down. - // (0x00000019) - int KEYCODE_VOLUME_DOWN = 25; - - // Key code constant: Volume Mute key. Mutes the speaker, unlike KEYCODE_MUTE. This key should normally be implemented as a toggle such that the first press mutes the speaker and the second press restores the original volume. - // (0x000000a4) - int KEYCODE_VOLUME_MUTE = 164; - - // Key code constant: Volume Up key. Adjusts the speaker volume up. - // (0x00000018) - int KEYCODE_VOLUME_UP = 24; - - // Key code constant: 'W' key. - // (0x00000033) - int KEYCODE_W = 51; - - // Key code constant: Wakeup key. Wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake. - // (0x000000e0) - int KEYCODE_WAKEUP = 224; - - // Key code constant: Window key. On TV remotes, toggles picture-in-picture mode or other windowing functions. - // (0x000000ab) - int KEYCODE_WINDOW = 171; - - // Key code constant: 'X' key. - // (0x00000034) - int KEYCODE_X = 52; - - // Key code constant: 'Y' key. - // (0x00000035) - int KEYCODE_Y = 53; - - // Key code constant: Japanese Yen key. - // (0x000000d8) - int KEYCODE_YEN = 216; - - // Key code constant: 'Z' key. - // (0x00000036) - int KEYCODE_Z = 54; - - // Key code constant: Japanese full-width / half-width key. - // (0x000000d3) - int KEYCODE_ZENKAKU_HANKAKU = 211; - - // Key code constant: Zoom in key. - // (0x000000a8) - int KEYCODE_ZOOM_IN = 168; - - // Key code constant: Zoom out key. - // (0x000000a9) - int KEYCODE_ZOOM_OUT = 169; - - // This constant was deprecated in API level 3. - // There are now more than MAX_KEYCODE keycodes. Use getMaxKeyCode() instead. - // (0x00000054) - int MAX_KEYCODE = 84; - - // This mask is used to check whether the left ALT meta key is pressed. - // See Also - // isAltPressed() - // getMetaState() - // KEYCODE_ALT_LEFT - // (0x00000010) - int META_ALT_LEFT_ON = 16; - - // This mask is a combination of META_ALT_ON, META_ALT_LEFT_ON and META_ALT_RIGHT_ON. - // (0x00000032) - int META_ALT_MASK = 50; - - // This mask is used to check whether one of the ALT meta keys is pressed. - // See Also - // isAltPressed() - // getMetaState() - // KEYCODE_ALT_LEFT - // KEYCODE_ALT_RIGHT - // (0x00000002) - int META_ALT_ON = 2; - - // This mask is used to check whether the right the ALT meta key is pressed. - // See Also - // isAltPressed() - // getMetaState() - // KEYCODE_ALT_RIGHT - // (0x00000020) - int META_ALT_RIGHT_ON = 32; - - // This mask is used to check whether the CAPS LOCK meta key is on. - // See Also - // isCapsLockOn() - // getMetaState() - // KEYCODE_CAPS_LOCK - // (0x00100000) - int META_CAPS_LOCK_ON = 1048576; - - // This mask is used to check whether the left CTRL meta key is pressed. - // See Also - // isCtrlPressed() - // getMetaState() - // KEYCODE_CTRL_LEFT - // (0x00002000) - int META_CTRL_LEFT_ON = 8192; - - // This mask is a combination of META_CTRL_ON, META_CTRL_LEFT_ON and META_CTRL_RIGHT_ON. - // (0x00007000) - int META_CTRL_MASK = 28672; - - // This mask is used to check whether one of the CTRL meta keys is pressed. - // See Also - // isCtrlPressed() - // getMetaState() - // KEYCODE_CTRL_LEFT - // KEYCODE_CTRL_RIGHT - // (0x00001000) - int META_CTRL_ON = 4096; - - // This mask is used to check whether the right CTRL meta key is pressed. - // See Also - // isCtrlPressed() - // getMetaState() - // KEYCODE_CTRL_RIGHT - // (0x00004000) - int META_CTRL_RIGHT_ON = 16384; - - // This mask is used to check whether the FUNCTION meta key is pressed. - // See Also - // isFunctionPressed() - // getMetaState() - // (0x00000008) - int META_FUNCTION_ON = 8; - - // This mask is used to check whether the left META meta key is pressed. - // See Also - // isMetaPressed() - // getMetaState() - // KEYCODE_META_LEFT - // (0x00020000) - int META_META_LEFT_ON = 131072; - - // This mask is a combination of META_META_ON, META_META_LEFT_ON and META_META_RIGHT_ON. - // (0x00070000) - int META_META_MASK = 458752; - - // This mask is used to check whether one of the META meta keys is pressed. - // See Also - // isMetaPressed() - // getMetaState() - // KEYCODE_META_LEFT - // KEYCODE_META_RIGHT - // (0x00010000) - int META_META_ON = 65536; - - // This mask is used to check whether the right META meta key is pressed. - // See Also - // isMetaPressed() - // getMetaState() - // KEYCODE_META_RIGHT - // (0x00040000) - int META_META_RIGHT_ON = 262144; - - // This mask is used to check whether the NUM LOCK meta key is on. - // See Also - // isNumLockOn() - // getMetaState() - // KEYCODE_NUM_LOCK - // (0x00200000) - int META_NUM_LOCK_ON = 2097152; - - // This mask is used to check whether the SCROLL LOCK meta key is on. - // See Also - // isScrollLockOn() - // getMetaState() - // KEYCODE_SCROLL_LOCK - // (0x00400000) - int META_SCROLL_LOCK_ON = 4194304; - - // This mask is used to check whether the left SHIFT meta key is pressed. - // See Also - // isShiftPressed() - // getMetaState() - // KEYCODE_SHIFT_LEFT - // (0x00000040) - int META_SHIFT_LEFT_ON = 64; - - // This mask is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON and META_SHIFT_RIGHT_ON. - // (0x000000c1) - int META_SHIFT_MASK = 193; - - // This mask is used to check whether one of the SHIFT meta keys is pressed. - // See Also - // isShiftPressed() - // getMetaState() - // KEYCODE_SHIFT_LEFT - // KEYCODE_SHIFT_RIGHT - // (0x00000001) - int META_SHIFT_ON = 1; - - // This mask is used to check whether the right SHIFT meta key is pressed. - // See Also - // isShiftPressed() - // getMetaState() - // KEYCODE_SHIFT_RIGHT - // (0x00000080) - int META_SHIFT_RIGHT_ON = 128; - - // This mask is used to check whether the SYM meta key is pressed. - // See Also - // isSymPressed() - // getMetaState() - // (0x00000004) - int META_SYM_ON = 4; + // Key code constant: BS/CS key. Toggles between BS and CS digital satellite services. + // (0x000000f0) + int KEYCODE_TV_SATELLITE_SERVICE = 240; + + // Key code constant: Teletext key. Displays Teletext service. + // (0x000000e9) + int KEYCODE_TV_TELETEXT = 233; + + // Key code constant: Analog Terrestrial key. Switches to analog terrestrial broadcast service. + // (0x000000eb) + int KEYCODE_TV_TERRESTRIAL_ANALOG = 235; + + // Key code constant: Digital Terrestrial key. Switches to digital terrestrial broadcast service. + // (0x000000ec) + int KEYCODE_TV_TERRESTRIAL_DIGITAL = 236; + + // Key code constant: Timer programming key. Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of CEC User Control Code. + // (0x00000102) + int KEYCODE_TV_TIMER_PROGRAMMING = 258; + + // Key code constant: Zoom mode key. Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) + // (0x000000ff) + int KEYCODE_TV_ZOOM_MODE = 255; + + // Key code constant: 'U' key. + // (0x00000031) + int KEYCODE_U = 49; + + // Key code constant: Unknown key code. + // (0x00000000) + int KEYCODE_UNKNOWN = 0; + + // Key code constant: 'V' key. + // (0x00000032) + int KEYCODE_V = 50; + + // Key code constant: Voice Assist key. Launches the global voice assist activity. Not delivered to applications. + // (0x000000e7) + int KEYCODE_VOICE_ASSIST = 231; + + // Key code constant: Volume Down key. Adjusts the speaker volume down. + // (0x00000019) + int KEYCODE_VOLUME_DOWN = 25; + + // Key code constant: Volume Mute key. Mutes the speaker, unlike KEYCODE_MUTE. This key should normally be implemented as a toggle such that the first press mutes the speaker and the second press restores the original volume. + // (0x000000a4) + int KEYCODE_VOLUME_MUTE = 164; + + // Key code constant: Volume Up key. Adjusts the speaker volume up. + // (0x00000018) + int KEYCODE_VOLUME_UP = 24; + + // Key code constant: 'W' key. + // (0x00000033) + int KEYCODE_W = 51; + + // Key code constant: Wakeup key. Wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake. + // (0x000000e0) + int KEYCODE_WAKEUP = 224; + + // Key code constant: Window key. On TV remotes, toggles picture-in-picture mode or other windowing functions. + // (0x000000ab) + int KEYCODE_WINDOW = 171; + + // Key code constant: 'X' key. + // (0x00000034) + int KEYCODE_X = 52; + + // Key code constant: 'Y' key. + // (0x00000035) + int KEYCODE_Y = 53; + + // Key code constant: Japanese Yen key. + // (0x000000d8) + int KEYCODE_YEN = 216; + + // Key code constant: 'Z' key. + // (0x00000036) + int KEYCODE_Z = 54; + + // Key code constant: Japanese full-width / half-width key. + // (0x000000d3) + int KEYCODE_ZENKAKU_HANKAKU = 211; + + // Key code constant: Zoom in key. + // (0x000000a8) + int KEYCODE_ZOOM_IN = 168; + + // Key code constant: Zoom out key. + // (0x000000a9) + int KEYCODE_ZOOM_OUT = 169; + + // This constant was deprecated in API level 3. + // There are now more than MAX_KEYCODE keycodes. Use getMaxKeyCode() instead. + // (0x00000054) + int MAX_KEYCODE = 84; + + // This mask is used to check whether the left ALT meta key is pressed. + // See Also + // isAltPressed() + // getMetaState() + // KEYCODE_ALT_LEFT + // (0x00000010) + int META_ALT_LEFT_ON = 16; + + // This mask is a combination of META_ALT_ON, META_ALT_LEFT_ON and META_ALT_RIGHT_ON. + // (0x00000032) + int META_ALT_MASK = 50; + + // This mask is used to check whether one of the ALT meta keys is pressed. + // See Also + // isAltPressed() + // getMetaState() + // KEYCODE_ALT_LEFT + // KEYCODE_ALT_RIGHT + // (0x00000002) + int META_ALT_ON = 2; + + // This mask is used to check whether the right the ALT meta key is pressed. + // See Also + // isAltPressed() + // getMetaState() + // KEYCODE_ALT_RIGHT + // (0x00000020) + int META_ALT_RIGHT_ON = 32; + + // This mask is used to check whether the CAPS LOCK meta key is on. + // See Also + // isCapsLockOn() + // getMetaState() + // KEYCODE_CAPS_LOCK + // (0x00100000) + int META_CAPS_LOCK_ON = 1048576; + + // This mask is used to check whether the left CTRL meta key is pressed. + // See Also + // isCtrlPressed() + // getMetaState() + // KEYCODE_CTRL_LEFT + // (0x00002000) + int META_CTRL_LEFT_ON = 8192; + + // This mask is a combination of META_CTRL_ON, META_CTRL_LEFT_ON and META_CTRL_RIGHT_ON. + // (0x00007000) + int META_CTRL_MASK = 28672; + + // This mask is used to check whether one of the CTRL meta keys is pressed. + // See Also + // isCtrlPressed() + // getMetaState() + // KEYCODE_CTRL_LEFT + // KEYCODE_CTRL_RIGHT + // (0x00001000) + int META_CTRL_ON = 4096; + + // This mask is used to check whether the right CTRL meta key is pressed. + // See Also + // isCtrlPressed() + // getMetaState() + // KEYCODE_CTRL_RIGHT + // (0x00004000) + int META_CTRL_RIGHT_ON = 16384; + + // This mask is used to check whether the FUNCTION meta key is pressed. + // See Also + // isFunctionPressed() + // getMetaState() + // (0x00000008) + int META_FUNCTION_ON = 8; + + // This mask is used to check whether the left META meta key is pressed. + // See Also + // isMetaPressed() + // getMetaState() + // KEYCODE_META_LEFT + // (0x00020000) + int META_META_LEFT_ON = 131072; + + // This mask is a combination of META_META_ON, META_META_LEFT_ON and META_META_RIGHT_ON. + // (0x00070000) + int META_META_MASK = 458752; + + // This mask is used to check whether one of the META meta keys is pressed. + // See Also + // isMetaPressed() + // getMetaState() + // KEYCODE_META_LEFT + // KEYCODE_META_RIGHT + // (0x00010000) + int META_META_ON = 65536; + + // This mask is used to check whether the right META meta key is pressed. + // See Also + // isMetaPressed() + // getMetaState() + // KEYCODE_META_RIGHT + // (0x00040000) + int META_META_RIGHT_ON = 262144; + + // This mask is used to check whether the NUM LOCK meta key is on. + // See Also + // isNumLockOn() + // getMetaState() + // KEYCODE_NUM_LOCK + // (0x00200000) + int META_NUM_LOCK_ON = 2097152; + + // This mask is used to check whether the SCROLL LOCK meta key is on. + // See Also + // isScrollLockOn() + // getMetaState() + // KEYCODE_SCROLL_LOCK + // (0x00400000) + int META_SCROLL_LOCK_ON = 4194304; + + // This mask is used to check whether the left SHIFT meta key is pressed. + // See Also + // isShiftPressed() + // getMetaState() + // KEYCODE_SHIFT_LEFT + // (0x00000040) + int META_SHIFT_LEFT_ON = 64; + + // This mask is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON and META_SHIFT_RIGHT_ON. + // (0x000000c1) + int META_SHIFT_MASK = 193; + + // This mask is used to check whether one of the SHIFT meta keys is pressed. + // See Also + // isShiftPressed() + // getMetaState() + // KEYCODE_SHIFT_LEFT + // KEYCODE_SHIFT_RIGHT + // (0x00000001) + int META_SHIFT_ON = 1; + + // This mask is used to check whether the right SHIFT meta key is pressed. + // See Also + // isShiftPressed() + // getMetaState() + // KEYCODE_SHIFT_RIGHT + // (0x00000080) + int META_SHIFT_RIGHT_ON = 128; + + // This mask is used to check whether the SYM meta key is pressed. + // See Also + // isSymPressed() + // getMetaState() + // (0x00000004) + int META_SYM_ON = 4; } diff --git a/src/main/java/io/appium/java_client/android/AndroidKeyMetastate.java b/src/main/java/io/appium/java_client/android/AndroidKeyMetastate.java index f4e8a00a1..2843f493b 100644 --- a/src/main/java/io/appium/java_client/android/AndroidKeyMetastate.java +++ b/src/main/java/io/appium/java_client/android/AndroidKeyMetastate.java @@ -21,21 +21,21 @@ */ public interface AndroidKeyMetastate { - int META_ALT_LEFT_ON = 16; - int META_ALT_ON = 2; - int META_ALT_RIGHT_ON = 32; - int META_CAPS_LOCK_ON = 1048576; - int META_CTRL_LEFT_ON = 8192; - int META_CTRL_ON = 4096; - int META_CTRL_RIGHT_ON = 16384; - int META_FUNCTION_ON = 8; - int META_META_LEFT_ON = 131072; - int META_META_ON = 65536; - int META_META_RIGHT_ON = 262144; - int META_NUM_LOCK_ON = 2097152; - int META_SCROLL_LOCK_ON = 4194304; - int META_SHIFT_LEFT_ON = 64; - int META_SHIFT_ON = 1; - int META_SHIFT_RIGHT_ON = 128; - int META_SYM_ON = 4; + int META_ALT_LEFT_ON = 16; + int META_ALT_ON = 2; + int META_ALT_RIGHT_ON = 32; + int META_CAPS_LOCK_ON = 1048576; + int META_CTRL_LEFT_ON = 8192; + int META_CTRL_ON = 4096; + int META_CTRL_RIGHT_ON = 16384; + int META_FUNCTION_ON = 8; + int META_META_LEFT_ON = 131072; + int META_META_ON = 65536; + int META_META_RIGHT_ON = 262144; + int META_NUM_LOCK_ON = 2097152; + int META_SCROLL_LOCK_ON = 4194304; + int META_SHIFT_LEFT_ON = 64; + int META_SHIFT_ON = 1; + int META_SHIFT_RIGHT_ON = 128; + int META_SYM_ON = 4; } diff --git a/src/main/java/io/appium/java_client/android/HasNetworkConnection.java b/src/main/java/io/appium/java_client/android/HasNetworkConnection.java index 01ecf3ed9..0024064ba 100644 --- a/src/main/java/io/appium/java_client/android/HasNetworkConnection.java +++ b/src/main/java/io/appium/java_client/android/HasNetworkConnection.java @@ -16,25 +16,24 @@ package io.appium.java_client.android; - import io.appium.java_client.NetworkConnectionSetting; +import io.appium.java_client.NetworkConnectionSetting; public interface HasNetworkConnection { - /** - * Get the current network settings of the device. - * - * @return NetworkConnectionSetting objects will let you inspect the status - * of AirplaneMode, Wifi, Data connections - */ - NetworkConnectionSetting getNetworkConnection(); + /** + * Get the current network settings of the device. + * + * @return NetworkConnectionSetting objects will let you inspect the status + * of AirplaneMode, Wifi, Data connections + */ + NetworkConnectionSetting getNetworkConnection(); - /** - * Set the network connection of the device. This is an Android-only method - * - * @param connection - * The NetworkConnectionSetting configuration to use for the - * device - */ - void setNetworkConnection(NetworkConnectionSetting connection); + /** + * Set the network connection of the device. This is an Android-only method + * + * @param connection The NetworkConnectionSetting configuration to use for the + * device + */ + void setNetworkConnection(NetworkConnectionSetting connection); } diff --git a/src/main/java/io/appium/java_client/android/PushesFiles.java b/src/main/java/io/appium/java_client/android/PushesFiles.java index ae469d158..3af0d6547 100644 --- a/src/main/java/io/appium/java_client/android/PushesFiles.java +++ b/src/main/java/io/appium/java_client/android/PushesFiles.java @@ -23,10 +23,8 @@ public interface PushesFiles extends InteractsWithFiles { /** * Save base64 encoded data as a file on the remote mobile device. * - * @param remotePath - * Path to file to write data to on remote device - * @param base64Data - * Base64 encoded byte array of data to write to remote device + * @param remotePath Path to file to write data to on remote device + * @param base64Data Base64 encoded byte array of data to write to remote device */ void pushFile(String remotePath, byte[] base64Data); diff --git a/src/main/java/io/appium/java_client/android/StartsActivity.java b/src/main/java/io/appium/java_client/android/StartsActivity.java index c93e7498c..9d8a19352 100644 --- a/src/main/java/io/appium/java_client/android/StartsActivity.java +++ b/src/main/java/io/appium/java_client/android/StartsActivity.java @@ -18,38 +18,37 @@ public interface StartsActivity { /** - * This method should start arbitrary activity during a test. If the activity belongs to - * another application, that application is started and the activity is opened. - * - * @param appPackage The package containing the activity. [Required] - * @param appActivity The activity to start. [Required] - * @param appWaitPackage Automation will begin after this package starts. [Optional] - * @param appWaitActivity Automation will begin after this activity starts. [Optional] - * @param stopApp If true, target app will be stopped. [Optional] - */ - void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity, - boolean stopApp) throws IllegalArgumentException; + * This method should start arbitrary activity during a test. If the activity belongs to + * another application, that application is started and the activity is opened. + * + * @param appPackage The package containing the activity. [Required] + * @param appActivity The activity to start. [Required] + * @param appWaitPackage Automation will begin after this package starts. [Optional] + * @param appWaitActivity Automation will begin after this activity starts. [Optional] + * @param stopApp If true, target app will be stopped. [Optional] + */ + void startActivity(String appPackage, String appActivity, String appWaitPackage, + String appWaitActivity, boolean stopApp) throws IllegalArgumentException; /** - * This method should start arbitrary activity during a test. If the activity belongs to - * another application, that application is started and the activity is opened. - * - * @param appPackage The package containing the activity. [Required] - * @param appActivity The activity to start. [Required] - * @param appWaitPackage Automation will begin after this package starts. [Optional] - * @param appWaitActivity Automation will begin after this activity starts. [Optional] - */ - void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity) - throws IllegalArgumentException; + * This method should start arbitrary activity during a test. If the activity belongs to + * another application, that application is started and the activity is opened. + * + * @param appPackage The package containing the activity. [Required] + * @param appActivity The activity to start. [Required] + * @param appWaitPackage Automation will begin after this package starts. [Optional] + * @param appWaitActivity Automation will begin after this activity starts. [Optional] + */ + void startActivity(String appPackage, String appActivity, String appWaitPackage, + String appWaitActivity) throws IllegalArgumentException; /** - * This method should start arbitrary activity during a test. If the activity belongs to - * another application, that application is started and the activity is opened. - * - * @param appPackage The package containing the activity. [Required] - * @param appActivity The activity to start. [Required] - */ - void startActivity(String appPackage, String appActivity) - throws IllegalArgumentException; + * This method should start arbitrary activity during a test. If the activity belongs to + * another application, that application is started and the activity is opened. + * + * @param appPackage The package containing the activity. [Required] + * @param appActivity The activity to start. [Required] + */ + void startActivity(String appPackage, String appActivity) throws IllegalArgumentException; } diff --git a/src/main/java/io/appium/java_client/android/internal/JsonToAndroidElementConverter.java b/src/main/java/io/appium/java_client/android/internal/JsonToAndroidElementConverter.java index 7a5cac599..bd9f84904 100644 --- a/src/main/java/io/appium/java_client/android/internal/JsonToAndroidElementConverter.java +++ b/src/main/java/io/appium/java_client/android/internal/JsonToAndroidElementConverter.java @@ -23,15 +23,14 @@ public class JsonToAndroidElementConverter extends JsonToMobileElementConverter { - public JsonToAndroidElementConverter(AppiumDriver driver) { - super(driver); - } + public JsonToAndroidElementConverter(AppiumDriver driver) { + super(driver); + } - @Override - protected MobileElement newMobileElement() { - AndroidElement toReturn = new AndroidElement(); - toReturn.setParent(driver); - return toReturn; - } + @Override protected MobileElement newMobileElement() { + AndroidElement toReturn = new AndroidElement(); + toReturn.setParent(driver); + return toReturn; + } } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByClassName.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByClassName.java index fee7bde2e..c7a4485f3 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByClassName.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByClassName.java @@ -22,5 +22,6 @@ public interface GenericFindsByClassName { T findElementByClassName(String className); + List findElementsByClassName(String className); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByCssSelector.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByCssSelector.java index 1da3a4190..5dcfa093b 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByCssSelector.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByCssSelector.java @@ -22,5 +22,6 @@ public interface GenericFindsByCssSelector { T findElementByCssSelector(String cssSelector); + List findElementsByCssSelector(String cssSelector); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsById.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsById.java index e54e2e033..98ce156b8 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsById.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsById.java @@ -22,5 +22,6 @@ public interface GenericFindsById { T findElementById(String id); + List findElementsById(String id); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByLinkText.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByLinkText.java index 00d9809e7..b48585d43 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByLinkText.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByLinkText.java @@ -22,7 +22,10 @@ public interface GenericFindsByLinkText { T findElementByLinkText(String linkText); + List findElementsByLinkText(String linkText); + T findElementByPartialLinkText(String partialLinkText); + List findElementsByPartialLinkText(String partialLinkText); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByName.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByName.java index 5afa61dea..ec1431009 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByName.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByName.java @@ -22,5 +22,6 @@ public interface GenericFindsByName { T findElementByName(String name); + List findElementsByName(String name); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByTagName.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByTagName.java index d3f43afea..98a22c333 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByTagName.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByTagName.java @@ -22,5 +22,6 @@ public interface GenericFindsByTagName { T findElementByTagName(String tagName); + List findElementsByTagName(String tagName); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByXPath.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByXPath.java index 361e6b031..1ba9f9897 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByXPath.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericFindsByXPath.java @@ -22,5 +22,6 @@ public interface GenericFindsByXPath { T findElementByXPath(String xPath); + List findElementsByXPath(String xPath); } diff --git a/src/main/java/io/appium/java_client/generic/searchcontext/GenericSearchContext.java b/src/main/java/io/appium/java_client/generic/searchcontext/GenericSearchContext.java index 8c31a473f..a7609df9e 100644 --- a/src/main/java/io/appium/java_client/generic/searchcontext/GenericSearchContext.java +++ b/src/main/java/io/appium/java_client/generic/searchcontext/GenericSearchContext.java @@ -23,5 +23,6 @@ public interface GenericSearchContext { List findElements(By by); + T findElement(By by); } diff --git a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java index c0961bc10..74dc67c70 100644 --- a/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java +++ b/src/main/java/io/appium/java_client/internal/JsonToMobileElementConverter.java @@ -16,18 +16,16 @@ package io.appium.java_client.internal; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; - -import java.util.Collection; -import java.util.Map; - import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.internal.JsonToWebElementConverter; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Map; /** * Reconstitutes {@link WebElement}s from their JSON representation. Will recursively convert Lists @@ -70,8 +68,8 @@ public Object apply(Object result) { } protected abstract MobileElement newMobileElement(); //{ - //MobileElement toReturn = new MobileElement(); - //toReturn.setParent(driver); - //return toReturn; + //MobileElement toReturn = new MobileElement(); + //toReturn.setParent(driver); + //return toReturn; //} } diff --git a/src/main/java/io/appium/java_client/internal/MobileElementToJsonConverter.java b/src/main/java/io/appium/java_client/internal/MobileElementToJsonConverter.java index 1daf92553..fe93e1bcc 100644 --- a/src/main/java/io/appium/java_client/internal/MobileElementToJsonConverter.java +++ b/src/main/java/io/appium/java_client/internal/MobileElementToJsonConverter.java @@ -16,19 +16,17 @@ package io.appium.java_client.internal; +import com.google.common.collect.Collections2; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import io.appium.java_client.MobileElement; - -import java.util.Collection; -import java.util.Map; - import org.openqa.selenium.internal.WrapsElement; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.remote.internal.WebElementToJsonConverter; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Map; /** * Converts {@link RemoteWebElement} objects, which may be @@ -37,48 +35,49 @@ * Maps to catch nested references. * * @see - * WebDriver JSON Wire Protocol + * WebDriver JSON Wire Protocol */ public class MobileElementToJsonConverter extends WebElementToJsonConverter { - public Object apply(Object arg) { - if (arg == null || arg instanceof String || arg instanceof Boolean || - arg instanceof Number) { - return arg; - } + public Object apply(Object arg) { + if (arg == null || arg instanceof String || arg instanceof Boolean || + arg instanceof Number) { + return arg; + } - while (arg instanceof WrapsElement) { - arg = ((WrapsElement) arg).getWrappedElement(); - } + while (arg instanceof WrapsElement) { + arg = ((WrapsElement) arg).getWrappedElement(); + } - if (arg instanceof MobileElement) { - return ImmutableMap.of("ELEMENT", ((MobileElement) arg).getId()); - } + if (arg instanceof MobileElement) { + return ImmutableMap.of("ELEMENT", ((MobileElement) arg).getId()); + } - if (arg.getClass().isArray()) { - arg = Lists.newArrayList((Object[]) arg); - } + if (arg.getClass().isArray()) { + arg = Lists.newArrayList((Object[]) arg); + } - if (arg instanceof Collection) { - Collection args = (Collection) arg; - return Collections2.transform(args, this); - } + if (arg instanceof Collection) { + Collection args = (Collection) arg; + return Collections2.transform(args, this); + } - if (arg instanceof Map) { - Map args = (Map) arg; - Map converted = Maps.newHashMapWithExpectedSize(args.size()); - for (Map.Entry entry : args.entrySet()) { - Object key = entry.getKey(); - if (!(key instanceof String)) { - throw new IllegalArgumentException( - "All keys in Map script arguments must be strings: " + key.getClass().getName()); + if (arg instanceof Map) { + Map args = (Map) arg; + Map converted = Maps.newHashMapWithExpectedSize(args.size()); + for (Map.Entry entry : args.entrySet()) { + Object key = entry.getKey(); + if (!(key instanceof String)) { + throw new IllegalArgumentException( + "All keys in Map script arguments must be strings: " + key.getClass() + .getName()); + } + converted.put((String) key, apply(entry.getValue())); + } + return converted; } - converted.put((String) key, apply(entry.getValue())); - } - return converted; - } - throw new IllegalArgumentException("Argument is of an illegal type: " - + arg.getClass().getName()); - } + throw new IllegalArgumentException( + "Argument is of an illegal type: " + arg.getClass().getName()); + } } diff --git a/src/main/java/io/appium/java_client/ios/GetsNamedTextField.java b/src/main/java/io/appium/java_client/ios/GetsNamedTextField.java index 561cb08d7..3a5c344e3 100644 --- a/src/main/java/io/appium/java_client/ios/GetsNamedTextField.java +++ b/src/main/java/io/appium/java_client/ios/GetsNamedTextField.java @@ -24,8 +24,7 @@ public interface GetsNamedTextField { * containing TableElement. This is a convenience method for getting the * named TextField, rather than its containing element. * - * @param name - * accessiblity id of TextField + * @param name accessiblity id of TextField * @return The textfield with the given accessibility id */ T getNamedTextField(String name); diff --git a/src/main/java/io/appium/java_client/ios/IOSDeviceActionShortcuts.java b/src/main/java/io/appium/java_client/ios/IOSDeviceActionShortcuts.java index 96ae54bf3..c461d2798 100644 --- a/src/main/java/io/appium/java_client/ios/IOSDeviceActionShortcuts.java +++ b/src/main/java/io/appium/java_client/ios/IOSDeviceActionShortcuts.java @@ -24,9 +24,8 @@ public interface IOSDeviceActionShortcuts extends DeviceActionShortcuts { * Hides the keyboard by pressing the button specified by keyName if it is * showing. * - * @param keyName - * The button pressed by the mobile driver to attempt hiding the - * keyboard + * @param keyName The button pressed by the mobile driver to attempt hiding the + * keyboard */ void hideKeyboard(String keyName); @@ -37,11 +36,9 @@ public interface IOSDeviceActionShortcuts extends DeviceActionShortcuts { * depends on the way an app is implemented, no single strategy always * works. * - * @param strategy - * HideKeyboardStrategy - * @param keyName - * a String, representing the text displayed on the button of the - * keyboard you want to press. For example: "Done" + * @param strategy HideKeyboardStrategy + * @param keyName a String, representing the text displayed on the button of the + * keyboard you want to press. For example: "Done" */ void hideKeyboard(String strategy, String keyName); diff --git a/src/main/java/io/appium/java_client/ios/IOSDriver.java b/src/main/java/io/appium/java_client/ios/IOSDriver.java index d396b806e..d9eb41219 100644 --- a/src/main/java/io/appium/java_client/ios/IOSDriver.java +++ b/src/main/java/io/appium/java_client/ios/IOSDriver.java @@ -17,148 +17,140 @@ package io.appium.java_client.ios; import com.google.common.collect.ImmutableMap; - import io.appium.java_client.AppiumDriver; import io.appium.java_client.FindsByAccessibilityId; import io.appium.java_client.FindsByIosUIAutomation; import io.appium.java_client.ScrollsTo; import io.appium.java_client.ios.internal.JsonToIOSElementConverter; import io.appium.java_client.remote.MobilePlatform; - import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; +import org.openqa.selenium.remote.http.HttpClient; import java.net.URL; import java.util.List; import static io.appium.java_client.MobileCommand.*; -import org.openqa.selenium.remote.http.HttpClient; /** * @param the required type of class which implement {@link org.openqa.selenium.WebElement}. - * Instances of the defined type will be returned via findElement* and findElements*. - * Warning (!!!). Allowed types: - * {@link org.openqa.selenium.WebElement} - * {@link io.appium.java_client.TouchableElement} - * {@link org.openqa.selenium.remote.RemoteWebElement} - * {@link io.appium.java_client.MobileElement} - * {@link io.appium.java_client.ios.IOSElement} + * Instances of the defined type will be returned via findElement* and findElements*. + * Warning (!!!). Allowed types: + * {@link org.openqa.selenium.WebElement} + * {@link io.appium.java_client.TouchableElement} + * {@link org.openqa.selenium.remote.RemoteWebElement} + * {@link io.appium.java_client.MobileElement} + * {@link io.appium.java_client.ios.IOSElement} */ -public class IOSDriver extends AppiumDriver implements IOSDeviceActionShortcuts, GetsNamedTextField, -FindsByIosUIAutomation{ +public class IOSDriver + extends AppiumDriver + implements IOSDeviceActionShortcuts, GetsNamedTextField, + FindsByIosUIAutomation { private static final String IOS_PLATFORM = MobilePlatform.IOS; public IOSDriver(URL remoteAddress, Capabilities desiredCapabilities) { - super(remoteAddress, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + super(remoteAddress, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } - - public IOSDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(remoteAddress, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + + public IOSDriver(URL remoteAddress, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(remoteAddress, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } public IOSDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities) { - super(service, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + super(service, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } - - public IOSDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(service, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + + public IOSDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(service, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } public IOSDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities) { - super(builder, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + super(builder, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } - - public IOSDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(builder, httpClientFactory, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + + public IOSDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory, + Capabilities desiredCapabilities) { + super(builder, httpClientFactory, + substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } - + public IOSDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) { - super(httpClientFactory, substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + super(httpClientFactory, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } public IOSDriver(Capabilities desiredCapabilities) { - super(substituteMobilePlatform(desiredCapabilities, - IOS_PLATFORM)); + super(substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM)); this.setElementConverter(new JsonToIOSElementConverter(this)); } - /** - * Scroll to the element whose 'text' attribute contains the input text. - * This scrolling happens within the first UIATableView on the UI. Use the method on IOSElement to scroll from a different ScrollView. - * @param text input text contained in text attribute - */ - @SuppressWarnings("unchecked") - @Override - public RequiredElementType scrollTo(String text) { - return (RequiredElementType) ((ScrollsTo) - findElementByClassName("UIATableView")).scrollTo(text); - } - - /** - * Scroll to the element whose 'text' attribute is equal to the input text. - * This scrolling happens within the first UIATableView on the UI. Use the method on IOSElement to scroll from a different ScrollView. - * @param text input text to match - */ - @SuppressWarnings("unchecked") - @Override - public RequiredElementType scrollToExact(String text) { - return (RequiredElementType) ((ScrollsTo) - findElementByClassName("UIATableView")).scrollToExact(text); - } - - /** + /** + * Scroll to the element whose 'text' attribute contains the input text. + * This scrolling happens within the first UIATableView on the UI. Use the method on IOSElement to scroll from a different ScrollView. + * + * @param text input text contained in text attribute + */ + @SuppressWarnings("unchecked") @Override public RequiredElementType scrollTo(String text) { + return (RequiredElementType) ((ScrollsTo) findElementByClassName("UIATableView")) + .scrollTo(text); + } + + /** + * Scroll to the element whose 'text' attribute is equal to the input text. + * This scrolling happens within the first UIATableView on the UI. Use the method on IOSElement to scroll from a different ScrollView. + * + * @param text input text to match + */ + @SuppressWarnings("unchecked") @Override public RequiredElementType scrollToExact(String text) { + return (RequiredElementType) ((ScrollsTo) findElementByClassName("UIATableView")) + .scrollToExact(text); + } + + /** * @see IOSDeviceActionShortcuts#hideKeyboard(String, String) */ - @Override - public void hideKeyboard(String strategy, String keyName) { - String[] parameters = new String[] { "strategy", "key" }; - Object[] values = new Object[] { strategy, keyName }; + @Override public void hideKeyboard(String strategy, String keyName) { + String[] parameters = new String[] {"strategy", "key"}; + Object[] values = new Object[] {strategy, keyName}; execute(HIDE_KEYBOARD, getCommandImmutableMap(parameters, values)); } /** * @see IOSDeviceActionShortcuts#hideKeyboard(String) */ - @Override - public void hideKeyboard(String keyName) { + @Override public void hideKeyboard(String keyName) { execute(HIDE_KEYBOARD, ImmutableMap.of("keyName", keyName)); } /** * @see IOSDeviceActionShortcuts#shake() */ - @Override - public void shake() { + @Override public void shake() { execute(SHAKE); } /** * @see GetsNamedTextField#getNamedTextField(String) */ - @SuppressWarnings("unchecked") - @Override - public RequiredElementType getNamedTextField(String name) { + @SuppressWarnings("unchecked") @Override public RequiredElementType getNamedTextField( + String name) { RequiredElementType element = findElementByAccessibilityId(name); if (element.getTagName() != "TextField") { return (RequiredElementType) ((FindsByAccessibilityId) element). - findElementByAccessibilityId(name); + findElementByAccessibilityId(name); } return element; } @@ -166,18 +158,18 @@ public RequiredElementType getNamedTextField(String name) { /** * @throws org.openqa.selenium.WebDriverException This method is not applicable with browser/webview UI. */ - @SuppressWarnings("unchecked") - @Override - public RequiredElementType findElementByIosUIAutomation(String using) throws WebDriverException { + @SuppressWarnings("unchecked") @Override + public RequiredElementType findElementByIosUIAutomation(String using) + throws WebDriverException { return (RequiredElementType) findElement("-ios uiautomation", using); } /** * @throws WebDriverException This method is not applicable with browser/webview UI. */ - @SuppressWarnings("unchecked") - @Override - public List findElementsByIosUIAutomation(String using) throws WebDriverException { + @SuppressWarnings("unchecked") @Override + public List findElementsByIosUIAutomation(String using) + throws WebDriverException { return (List) findElements("-ios uiautomation", using); } @@ -185,8 +177,7 @@ public List findElementsByIosUIAutomation(String using) thr * Lock the device (bring it to the lock screen) for a given number of * seconds * - * @param seconds - * number of seconds to lock the screen for + * @param seconds number of seconds to lock the screen for */ public void lockDevice(int seconds) { execute(LOCK, ImmutableMap.of("seconds", seconds)); diff --git a/src/main/java/io/appium/java_client/ios/IOSElement.java b/src/main/java/io/appium/java_client/ios/IOSElement.java index 9e35ce85e..3477229e6 100644 --- a/src/main/java/io/appium/java_client/ios/IOSElement.java +++ b/src/main/java/io/appium/java_client/ios/IOSElement.java @@ -16,64 +16,63 @@ package io.appium.java_client.ios; +import com.google.common.collect.ImmutableMap; import io.appium.java_client.FindsByIosUIAutomation; import io.appium.java_client.MobileCommand; import io.appium.java_client.MobileElement; import io.appium.java_client.ScrollsTo; - import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; -import com.google.common.collect.ImmutableMap; - import java.util.ArrayList; import java.util.List; -public class IOSElement extends MobileElement implements -FindsByIosUIAutomation, ScrollsTo { +public class IOSElement extends MobileElement + implements FindsByIosUIAutomation, ScrollsTo { /** * @throws org.openqa.selenium.WebDriverException This method is not applicable with browser/webview UI. */ - @Override - public MobileElement findElementByIosUIAutomation(String using) throws WebDriverException { + @Override public MobileElement findElementByIosUIAutomation(String using) + throws WebDriverException { return (IOSElement) findElement("-ios uiautomation", using); } /** * @throws WebDriverException This method is not applicable with browser/webview UI. */ - @Override - public List findElementsByIosUIAutomation(String using) throws WebDriverException { + @Override public List findElementsByIosUIAutomation(String using) + throws WebDriverException { List result = new ArrayList(); List found = findElements("-ios uiautomation", using); - for (WebElement e: found) + for (WebElement e : found) result.add((IOSElement) e); return result; } - /** - * Scroll to the element whose 'text' attribute contains the input text. - * Scrolling happens within this element - * @param text input text contained in text attribute - */ - @Override - public MobileElement scrollTo(String text) { - return (IOSElement) findElementByIosUIAutomation(".scrollToElementWithPredicate(\"name CONTAINS '" + text + "'\")"); + /** + * Scroll to the element whose 'text' attribute contains the input text. + * Scrolling happens within this element + * + * @param text input text contained in text attribute + */ + @Override public MobileElement scrollTo(String text) { + return (IOSElement) findElementByIosUIAutomation( + ".scrollToElementWithPredicate(\"name CONTAINS '" + text + "'\")"); } - /** - * Scroll to the element whose 'text' attribute matches the input text. - * Scrolling happens within this element - * @param text input text contained in text attribute - */ - @Override - public MobileElement scrollToExact(String text) { - return (IOSElement) findElementByIosUIAutomation(".scrollToElementWithName(\"" + text + "\")"); + /** + * Scroll to the element whose 'text' attribute matches the input text. + * Scrolling happens within this element + * + * @param text input text contained in text attribute + */ + @Override public MobileElement scrollToExact(String text) { + return (IOSElement) findElementByIosUIAutomation( + ".scrollToElementWithName(\"" + text + "\")"); } - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void setValue(String value) { + @SuppressWarnings({"rawtypes", "unchecked"}) public void setValue(String value) { ImmutableMap.Builder builder = ImmutableMap.builder(); builder.put("id", id).put("value", value); execute(MobileCommand.SET_VALUE, builder.build()); diff --git a/src/main/java/io/appium/java_client/ios/IOSKeyCode.java b/src/main/java/io/appium/java_client/ios/IOSKeyCode.java index 98453cea2..b0c0353aa 100644 --- a/src/main/java/io/appium/java_client/ios/IOSKeyCode.java +++ b/src/main/java/io/appium/java_client/ios/IOSKeyCode.java @@ -21,9 +21,9 @@ */ public interface IOSKeyCode { - int BACKSPACE = 8; - int ENTER = 13; - int RETURN = 13; - int SPACE = 32; + int BACKSPACE = 8; + int ENTER = 13; + int RETURN = 13; + int SPACE = 32; } diff --git a/src/main/java/io/appium/java_client/ios/internal/JsonToIOSElementConverter.java b/src/main/java/io/appium/java_client/ios/internal/JsonToIOSElementConverter.java index 36f76910f..38333341d 100644 --- a/src/main/java/io/appium/java_client/ios/internal/JsonToIOSElementConverter.java +++ b/src/main/java/io/appium/java_client/ios/internal/JsonToIOSElementConverter.java @@ -23,15 +23,14 @@ public class JsonToIOSElementConverter extends JsonToMobileElementConverter { - public JsonToIOSElementConverter(AppiumDriver driver) { - super(driver); - } + public JsonToIOSElementConverter(AppiumDriver driver) { + super(driver); + } - @Override - protected MobileElement newMobileElement() { - IOSElement toReturn = new IOSElement(); - toReturn.setParent(driver); - return toReturn; - } + @Override protected MobileElement newMobileElement() { + IOSElement toReturn = new IOSElement(); + toReturn.setParent(driver); + return toReturn; + } } diff --git a/src/main/java/io/appium/java_client/pagefactory/AndroidFindAll.java b/src/main/java/io/appium/java_client/pagefactory/AndroidFindAll.java index b69f22a9b..717475957 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AndroidFindAll.java +++ b/src/main/java/io/appium/java_client/pagefactory/AndroidFindAll.java @@ -26,8 +26,7 @@ * It will then search for all elements that match any criteria. Note that elements * are not guaranteed to be in document order. */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface AndroidFindAll { - AndroidFindBy[] value(); + AndroidFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java index 5569fe839..0811e3983 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBy.java @@ -29,18 +29,24 @@ * this allows users to quickly and easily create PageObjects. * using Android UI selectors, accessibility, id, name, class name, tag and xpath */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface AndroidFindBy { - String uiAutomator() default ""; - String accessibility() default ""; - String id() default ""; - @Deprecated - /** - * By.name selector is not supported by Appium server node since 1.5.x. - * So this option is going to be removed further. Be careful. - */String name() default ""; - String className() default ""; - String tagName() default ""; - String xpath() default ""; + String uiAutomator() default ""; + + String accessibility() default ""; + + String id() default ""; + + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */ + String name() default ""; + + String className() default ""; + + String tagName() default ""; + + String xpath() default ""; } diff --git a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBys.java b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBys.java index 4e9f695f4..95ceefdc9 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AndroidFindBys.java +++ b/src/main/java/io/appium/java_client/pagefactory/AndroidFindBys.java @@ -24,8 +24,7 @@ /** * Used to mark a field on a Page Object to indicate that lookup should use a series of @AndroidFindBy tags */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface AndroidFindBys { - AndroidFindBy[] value(); + AndroidFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java index 60b61ccf0..dfdeb9ceb 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java @@ -16,92 +16,40 @@ package io.appium.java_client.pagefactory; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - +import com.google.common.base.Function; import io.appium.java_client.pagefactory.locator.CacheableLocator; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.FluentWait; -import com.google.common.base.Function; -import static io.appium.java_client.pagefactory.ThrowableUtil.extractReadableException; -import static io.appium.java_client.pagefactory.ThrowableUtil.isInvalidSelectorRootCause; -import static io.appium.java_client.pagefactory.ThrowableUtil.isStaleElementReferenceException; - -class AppiumElementLocator implements CacheableLocator { - - // This function waits for not empty element list using all defined by - private static class WaitingFunction implements - Function> { - private final SearchContext searchContext; - Throwable foundStaleElementReferenceException; - - private WaitingFunction(SearchContext searchContext) { - this.searchContext = searchContext; - } - - public List apply(By by) { - List result = new ArrayList<>(); - Throwable shouldBeThrown = null; - boolean isRootCauseInvalidSelector; - boolean isRootCauseStaleElementReferenceException = false; - foundStaleElementReferenceException = null; - - try { - result.addAll(searchContext.findElements(by)); - } catch (Throwable e) { - - isRootCauseInvalidSelector = isInvalidSelectorRootCause(e); - if (!isRootCauseInvalidSelector) { - isRootCauseStaleElementReferenceException = isStaleElementReferenceException(e); - } - - if (isRootCauseStaleElementReferenceException) { - foundStaleElementReferenceException = extractReadableException(e); - } - - if (!isRootCauseInvalidSelector & !isRootCauseStaleElementReferenceException) { - shouldBeThrown = extractReadableException(e); - } - } +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; - if (shouldBeThrown != null) { - if (RuntimeException.class.isAssignableFrom(shouldBeThrown.getClass())) { - throw (RuntimeException) shouldBeThrown; - } - throw new RuntimeException(shouldBeThrown); - } +import static io.appium.java_client.pagefactory.ThrowableUtil.*; - if (result.size() > 0) { - return result; - } else { - return null; - } - } - } +class AppiumElementLocator implements CacheableLocator { - private final SearchContext searchContext; final boolean shouldCache; final By by; - private WebElement cachedElement; - private List cachedElementList; final TimeOutDuration timeOutDuration; final WebDriver originalWebDriver; + private final SearchContext searchContext; private final WaitingFunction waitingFunction; - + private WebElement cachedElement; + private List cachedElementList; /** * Creates a new mobile element locator. It instantiates {@link WebElement} * using @AndroidFindBy (-s), @iOSFindBy (-s) and @FindBy (-s) annotation * sets - * @param searchContext - * The context to use when finding the element - * @param by a By locator strategy - * @param shouldCache is the flag that signalizes that elements which are found once should be cached - * @param duration is a POJO which contains timeout parameters + * + * @param searchContext The context to use when finding the element + * @param by a By locator strategy + * @param shouldCache is the flag that signalizes that elements which are found once should be cached + * @param duration is a POJO which contains timeout parameters * @param originalWebDriver */ - public AppiumElementLocator(SearchContext searchContext, By by, boolean shouldCache, TimeOutDuration duration, WebDriver originalWebDriver) { + public AppiumElementLocator(SearchContext searchContext, By by, boolean shouldCache, + TimeOutDuration duration, WebDriver originalWebDriver) { this.searchContext = searchContext; this.shouldCache = shouldCache; this.timeOutDuration = duration; @@ -110,8 +58,7 @@ public AppiumElementLocator(SearchContext searchContext, By by, boolean shouldCa waitingFunction = new WaitingFunction(this.searchContext); } - private void changeImplicitlyWaitTimeOut(long newTimeOut, - TimeUnit newTimeUnit) { + private void changeImplicitlyWaitTimeOut(long newTimeOut, TimeUnit newTimeUnit) { originalWebDriver.manage().timeouts().implicitlyWait(newTimeOut, newTimeUnit); } @@ -124,14 +71,12 @@ private List waitFor() { try { changeImplicitlyWaitTimeOut(0, TimeUnit.SECONDS); FluentWait wait = new FluentWait<>(by); - wait.withTimeout(timeOutDuration.getTime(), - timeOutDuration.getTimeUnit()); + wait.withTimeout(timeOutDuration.getTime(), timeOutDuration.getTimeUnit()); return wait.until(waitingFunction); } catch (TimeoutException e) { return new ArrayList<>(); } finally { - changeImplicitlyWaitTimeOut(timeOutDuration.getTime(), - timeOutDuration.getTimeUnit()); + changeImplicitlyWaitTimeOut(timeOutDuration.getTime(), timeOutDuration.getTimeUnit()); } } @@ -144,10 +89,10 @@ public WebElement findElement() { } List result = waitFor(); if (result.size() == 0) { - String message = "Can't locate an element by this strategy: " - + by.toString(); + String message = "Can't locate an element by this strategy: " + by.toString(); if (waitingFunction.foundStaleElementReferenceException != null) { - throw new NoSuchElementException(message, waitingFunction.foundStaleElementReferenceException); + throw new NoSuchElementException(message, + waitingFunction.foundStaleElementReferenceException); } throw new NoSuchElementException(message); } @@ -171,8 +116,57 @@ public List findElements() { return result; } - @Override - public boolean isLookUpCached() { + @Override public boolean isLookUpCached() { return shouldCache; } + + + // This function waits for not empty element list using all defined by + private static class WaitingFunction implements Function> { + private final SearchContext searchContext; + Throwable foundStaleElementReferenceException; + + private WaitingFunction(SearchContext searchContext) { + this.searchContext = searchContext; + } + + public List apply(By by) { + List result = new ArrayList<>(); + Throwable shouldBeThrown = null; + boolean isRootCauseInvalidSelector; + boolean isRootCauseStaleElementReferenceException = false; + foundStaleElementReferenceException = null; + + try { + result.addAll(searchContext.findElements(by)); + } catch (Throwable e) { + + isRootCauseInvalidSelector = isInvalidSelectorRootCause(e); + if (!isRootCauseInvalidSelector) { + isRootCauseStaleElementReferenceException = isStaleElementReferenceException(e); + } + + if (isRootCauseStaleElementReferenceException) { + foundStaleElementReferenceException = extractReadableException(e); + } + + if (!isRootCauseInvalidSelector & !isRootCauseStaleElementReferenceException) { + shouldBeThrown = extractReadableException(e); + } + } + + if (shouldBeThrown != null) { + if (RuntimeException.class.isAssignableFrom(shouldBeThrown.getClass())) { + throw (RuntimeException) shouldBeThrown; + } + throw new RuntimeException(shouldBeThrown); + } + + if (result.size() > 0) { + return result; + } else { + return null; + } + } + } } diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java index ece053753..d8f013a47 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocatorFactory.java @@ -16,9 +16,6 @@ package io.appium.java_client.pagefactory; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; - import io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder; import io.appium.java_client.pagefactory.locator.CacheableElementLocatorFactory; import io.appium.java_client.pagefactory.locator.CacheableLocator; @@ -26,16 +23,17 @@ import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Field; + class AppiumElementLocatorFactory implements CacheableElementLocatorFactory { private final SearchContext searchContext; private final TimeOutDuration timeOutDuration; private final WebDriver originalWebDriver; private final AppiumByBuilder builder; - public AppiumElementLocatorFactory(SearchContext searchContext, - TimeOutDuration timeOutDuration, - WebDriver originalWebDriver, - AppiumByBuilder builder) { + public AppiumElementLocatorFactory(SearchContext searchContext, TimeOutDuration timeOutDuration, + WebDriver originalWebDriver, AppiumByBuilder builder) { this.searchContext = searchContext; this.originalWebDriver = originalWebDriver; this.timeOutDuration = timeOutDuration; @@ -46,21 +44,20 @@ public CacheableLocator createLocator(Field field) { return this.createLocator((AnnotatedElement) field); } - @Override - public CacheableLocator createLocator(AnnotatedElement annotatedElement) { + @Override public CacheableLocator createLocator(AnnotatedElement annotatedElement) { TimeOutDuration customDuration; if (annotatedElement.isAnnotationPresent(WithTimeout.class)) { WithTimeout withTimeout = annotatedElement.getAnnotation(WithTimeout.class); customDuration = new TimeOutDuration(withTimeout.time(), withTimeout.unit()); - } - else { + } else { customDuration = timeOutDuration; } builder.setAnnotated(annotatedElement); By by = builder.buildBy(); if (by != null) - return new AppiumElementLocator(searchContext, by, builder.isLookupCached(), customDuration, originalWebDriver); + return new AppiumElementLocator(searchContext, by, builder.isLookupCached(), + customDuration, originalWebDriver); return null; } diff --git a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java index 30ee14a81..b6350c3db 100644 --- a/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java +++ b/src/main/java/io/appium/java_client/pagefactory/AppiumFieldDecorator.java @@ -22,14 +22,6 @@ import io.appium.java_client.android.AndroidElement; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; -import java.util.concurrent.TimeUnit; - import io.appium.java_client.pagefactory.bys.ContentType; import io.appium.java_client.pagefactory.locator.CacheableLocator; import org.openqa.selenium.SearchContext; @@ -40,10 +32,18 @@ import org.openqa.selenium.support.pagefactory.ElementLocator; import org.openqa.selenium.support.pagefactory.FieldDecorator; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + import static io.appium.java_client.pagefactory.utils.ProxyFactory.getEnhancedProxy; -import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getAutomation; -import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getPlatform; -import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.unpackWebDriverFromSearchContext; +import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.*; /** * Default decorator for use with PageFactory. Will decorate 1) all of the @@ -51,36 +51,40 @@ * {@literal @AndroidFindBy}, {@literal @AndroidFindBys}, or * {@literal @iOSFindBy/@iOSFindBys} annotation with a proxy that locates the * elements using the passed in ElementLocatorFactory. - * + *

* Please pay attention: fields of {@link WebElement}, {@link RemoteWebElement}, - * {@link MobileElement}, {@link AndroidElement} and {@link IOSElement} are allowed + * {@link MobileElement}, {@link AndroidElement} and {@link IOSElement} are allowed * to use with this decorator */ -public class AppiumFieldDecorator implements FieldDecorator{ +public class AppiumFieldDecorator implements FieldDecorator { private static final List> availableElementClasses = - new ArrayList>() { - private static final long serialVersionUID = 1L; - { - add(WebElement.class); - add(RemoteWebElement.class); - add(MobileElement.class); - add(TouchableElement.class); - add(AndroidElement.class); - add(IOSElement.class); - } + new ArrayList>() { + private static final long serialVersionUID = 1L; + + { + add(WebElement.class); + add(RemoteWebElement.class); + add(MobileElement.class); + add(TouchableElement.class); + add(AndroidElement.class); + add(IOSElement.class); + } - }; + }; - private final static Map, Class> elementRuleMap = - new HashMap, Class>() { - private static final long serialVersionUID = 1L; - { - put(AndroidDriver.class, AndroidElement.class); - put(IOSDriver.class, IOSElement.class); - } - }; + private final static Map, Class> + elementRuleMap = + new HashMap, Class>() { + private static final long serialVersionUID = 1L; + { + put(AndroidDriver.class, AndroidElement.class); + put(IOSDriver.class, IOSElement.class); + } + }; + public static long DEFAULT_IMPLICITLY_WAIT_TIMEOUT = 1; + public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS; private final WebDriver originalDriver; private final DefaultFieldDecorator defaultElementFieldDecoracor; private final AppiumElementLocatorFactory widgetLocatorFactory; @@ -88,10 +92,8 @@ public class AppiumFieldDecorator implements FieldDecorator{ private final String automation; private final TimeOutDuration timeOutDuration; - public static long DEFAULT_IMPLICITLY_WAIT_TIMEOUT = 1; - public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS; - - public AppiumFieldDecorator(SearchContext context, long implicitlyWaitTimeOut, TimeUnit timeUnit) { + public AppiumFieldDecorator(SearchContext context, long implicitlyWaitTimeOut, + TimeUnit timeUnit) { this(context, new TimeOutDuration(implicitlyWaitTimeOut, timeUnit)); } @@ -102,23 +104,21 @@ public AppiumFieldDecorator(SearchContext context, TimeOutDuration timeOutDurati this.timeOutDuration = timeOutDuration; defaultElementFieldDecoracor = new DefaultFieldDecorator( - new AppiumElementLocatorFactory(context, timeOutDuration, originalDriver, - new DefaultElementByBuilder(platform, automation))) { + new AppiumElementLocatorFactory(context, timeOutDuration, originalDriver, + new DefaultElementByBuilder(platform, automation))) { @Override protected WebElement proxyForLocator(ClassLoader ignored, ElementLocator locator) { return proxyForAnElement(locator); } - @Override - @SuppressWarnings("unchecked") - protected List proxyForListLocator(ClassLoader ignored, ElementLocator locator) { + @Override @SuppressWarnings("unchecked") + protected List proxyForListLocator(ClassLoader ignored, + ElementLocator locator) { ElementListInterceptor elementInterceptor = new ElementListInterceptor(locator); - return getEnhancedProxy(ArrayList.class, - elementInterceptor); + return getEnhancedProxy(ArrayList.class, elementInterceptor); } - @Override - protected boolean isDecoratableList(Field field) { + @Override protected boolean isDecoratableList(Field field) { if (!List.class.isAssignableFrom(field.getType())) { return false; } @@ -131,8 +131,7 @@ protected boolean isDecoratableList(Field field) { Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0]; boolean result = false; - for (Class webElementClass: - availableElementClasses) { + for (Class webElementClass : availableElementClasses) { if (!webElementClass.equals(listType)) { continue; } @@ -143,7 +142,8 @@ protected boolean isDecoratableList(Field field) { } }; - widgetLocatorFactory = new AppiumElementLocatorFactory(context, timeOutDuration, originalDriver, + widgetLocatorFactory = + new AppiumElementLocatorFactory(context, timeOutDuration, originalDriver, new WidgetByBuilder(platform, automation)); } @@ -160,8 +160,7 @@ public Object decorate(ClassLoader ignored, Field field) { return decorateWidget(field); } - @SuppressWarnings("unchecked") - private Object decorateWidget(Field field) { + @SuppressWarnings("unchecked") private Object decorateWidget(Field field) { Class type = field.getType(); if (!Widget.class.isAssignableFrom(type) && !List.class.isAssignableFrom(type)) { return null; @@ -187,29 +186,31 @@ private Object decorateWidget(Field field) { } widgetType = Class.class.cast(listType); - } - else { + } else { widgetType = (Class) field.getType(); } CacheableLocator locator = widgetLocatorFactory.createLocator(field); Map> map = - OverrideWidgetReader.read(widgetType, field, platform, automation); + OverrideWidgetReader.read(widgetType, field, platform, automation); if (isAlist) { return getEnhancedProxy(ArrayList.class, - new WidgetListInterceptor(locator, originalDriver, map, widgetType, timeOutDuration)); + new WidgetListInterceptor(locator, originalDriver, map, widgetType, + timeOutDuration)); } - Constructor constructor = WidgetConstructorUtil.findConvenientConstructor(widgetType); + Constructor constructor = + WidgetConstructorUtil.findConvenientConstructor(widgetType); return getEnhancedProxy(widgetType, new Class[] {constructor.getParameterTypes()[0]}, - new Object[] {proxyForAnElement(locator)}, new WidgetInterceptor(locator, originalDriver, null, map, - timeOutDuration)); + new Object[] {proxyForAnElement(locator)}, + new WidgetInterceptor(locator, originalDriver, null, map, timeOutDuration)); } private Class getTypeForProxy() { Class driverClass = originalDriver.getClass(); - Iterable, Class>> rules = elementRuleMap.entrySet(); + Iterable, Class>> rules = + elementRuleMap.entrySet(); //it will return MobileElement subclass when here is something for (Map.Entry, Class> e : rules) { //that extends AppiumDriver or MobileElement @@ -220,7 +221,7 @@ private Class getTypeForProxy() { return RemoteWebElement.class; } - private WebElement proxyForAnElement(ElementLocator locator) { + private WebElement proxyForAnElement(ElementLocator locator) { ElementInterceptor elementInterceptor = new ElementInterceptor(locator, originalDriver); return (WebElement) getEnhancedProxy(getTypeForProxy(), elementInterceptor); } diff --git a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java index 3e581a0e4..0cf37f9ae 100644 --- a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java @@ -16,11 +16,6 @@ package io.appium.java_client.pagefactory; -import java.lang.annotation.Annotation; -import java.lang.reflect.*; -import java.util.HashMap; -import java.util.Map; - import io.appium.java_client.pagefactory.bys.ContentMappedBy; import io.appium.java_client.pagefactory.bys.ContentType; import io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder; @@ -28,34 +23,38 @@ import org.openqa.selenium.By; import org.openqa.selenium.support.*; +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + class DefaultElementByBuilder extends AppiumByBuilder { - private static void checkDisallowedAnnotationPairs(Annotation a1, - Annotation a2) throws IllegalArgumentException { + protected DefaultElementByBuilder(String platform, String automation) { + super(platform, automation); + } + + private static void checkDisallowedAnnotationPairs(Annotation a1, Annotation a2) + throws IllegalArgumentException { if (a1 != null && a2 != null) { - throw new IllegalArgumentException("If you use a '@" - + a1.getClass().getSimpleName() + "' annotation, " - + "you must not also use a '@" - + a2.getClass().getSimpleName() + "' annotation"); + throw new IllegalArgumentException( + "If you use a '@" + a1.getClass().getSimpleName() + "' annotation, " + + "you must not also use a '@" + a2.getClass().getSimpleName() + + "' annotation"); } } - @Override - protected void assertValidAnnotations() { + @Override protected void assertValidAnnotations() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); - AndroidFindBy androidBy = annotatedElement - .getAnnotation(AndroidFindBy.class); - AndroidFindBys androidBys = annotatedElement - .getAnnotation(AndroidFindBys.class); - AndroidFindAll androidFindAll = annotatedElement - .getAnnotation(AndroidFindAll.class); - - SelendroidFindBy selendroidBy = annotatedElement - .getAnnotation(SelendroidFindBy.class); - SelendroidFindBys selendroidBys = annotatedElement - .getAnnotation(SelendroidFindBys.class); - SelendroidFindAll selendroidFindAll = annotatedElement - .getAnnotation(SelendroidFindAll.class); + AndroidFindBy androidBy = annotatedElement.getAnnotation(AndroidFindBy.class); + AndroidFindBys androidBys = annotatedElement.getAnnotation(AndroidFindBys.class); + AndroidFindAll androidFindAll = annotatedElement.getAnnotation(AndroidFindAll.class); + + SelendroidFindBy selendroidBy = annotatedElement.getAnnotation(SelendroidFindBy.class); + SelendroidFindBys selendroidBys = annotatedElement.getAnnotation(SelendroidFindBys.class); + SelendroidFindAll selendroidFindAll = + annotatedElement.getAnnotation(SelendroidFindAll.class); iOSFindBy iOSBy = annotatedElement.getAnnotation(iOSFindBy.class); iOSFindBys iOSBys = annotatedElement.getAnnotation(iOSFindBys.class); @@ -82,12 +81,7 @@ protected void assertValidAnnotations() { checkDisallowedAnnotationPairs(findBys, findAll); } - protected DefaultElementByBuilder(String platform, String automation) { - super(platform, automation); - } - - @Override - protected By buildDefaultBy() { + @Override protected By buildDefaultBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); By defaultBy = null; FindBy findBy = annotatedElement.getAnnotation(FindBy.class); @@ -111,16 +105,18 @@ protected By buildDefaultBy() { return defaultBy; } - @Override - protected By buildMobileNativeBy() { + @Override protected By buildMobileNativeBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); if (isSelendroidAutomation()) { - SelendroidFindBy selendroidFindBy = annotatedElement.getAnnotation(SelendroidFindBy.class); - SelendroidFindBys selendroidFindBys = annotatedElement.getAnnotation(SelendroidFindBys.class); - SelendroidFindAll selendroidFindByAll = annotatedElement.getAnnotation(SelendroidFindAll.class); + SelendroidFindBy selendroidFindBy = + annotatedElement.getAnnotation(SelendroidFindBy.class); + SelendroidFindBys selendroidFindBys = + annotatedElement.getAnnotation(SelendroidFindBys.class); + SelendroidFindAll selendroidFindByAll = + annotatedElement.getAnnotation(SelendroidFindAll.class); if (selendroidFindBy != null) { - return createBy(new Annotation[]{selendroidFindBy}, HowToUseSelectors.USE_ONE); + return createBy(new Annotation[] {selendroidFindBy}, HowToUseSelectors.USE_ONE); } if (selendroidFindBys != null) { @@ -134,11 +130,11 @@ protected By buildMobileNativeBy() { if (isAndroid()) { AndroidFindBy androidFindBy = annotatedElement.getAnnotation(AndroidFindBy.class); - AndroidFindBys androidFindBys= annotatedElement.getAnnotation(AndroidFindBys.class); + AndroidFindBys androidFindBys = annotatedElement.getAnnotation(AndroidFindBys.class); AndroidFindAll androidFindAll = annotatedElement.getAnnotation(AndroidFindAll.class); if (androidFindBy != null) { - return createBy(new Annotation[]{androidFindBy}, HowToUseSelectors.USE_ONE); + return createBy(new Annotation[] {androidFindBy}, HowToUseSelectors.USE_ONE); } if (androidFindBys != null) { @@ -152,11 +148,11 @@ protected By buildMobileNativeBy() { if (isIOS()) { iOSFindBy iOSFindBy = annotatedElement.getAnnotation(iOSFindBy.class); - iOSFindBys iOSFindBys= annotatedElement.getAnnotation(iOSFindBys.class); + iOSFindBys iOSFindBys = annotatedElement.getAnnotation(iOSFindBys.class); iOSFindAll iOSFindAll = annotatedElement.getAnnotation(iOSFindAll.class); if (iOSFindBy != null) { - return createBy(new Annotation[]{iOSFindBy}, HowToUseSelectors.USE_ONE); + return createBy(new Annotation[] {iOSFindBy}, HowToUseSelectors.USE_ONE); } if (iOSFindBys != null) { @@ -171,8 +167,7 @@ protected By buildMobileNativeBy() { return null; } - @Override - public boolean isLookupCached() { + @Override public boolean isLookupCached() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); return (annotatedElement.getAnnotation(CacheLookup.class) != null); } @@ -184,8 +179,7 @@ private By returnMappedBy(By byDefault, By nativeAppBy) { return new ContentMappedBy(contentMap); } - @Override - public By buildBy() { + @Override public By buildBy() { assertValidAnnotations(); By defaultBy = buildDefaultBy(); @@ -194,13 +188,15 @@ public By buildBy() { String idOrName = ((Field) annotatedElementContainer.getAnnotated()).getName(); if (defaultBy == null && mobileNativeBy == null) { - defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); + defaultBy = + new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); mobileNativeBy = new By.ById(idOrName); return returnMappedBy(defaultBy, mobileNativeBy); } if (defaultBy == null) { - defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); + defaultBy = + new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); return returnMappedBy(defaultBy, mobileNativeBy); } diff --git a/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java index f5a9c4f46..5a0b58fdc 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/ElementInterceptor.java @@ -17,29 +17,28 @@ package io.appium.java_client.pagefactory; import io.appium.java_client.MobileElement; -import java.lang.reflect.Method; import io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.pagefactory.ElementLocator; +import java.lang.reflect.Method; + /** * Intercepts requests to {@link MobileElement} - * */ class ElementInterceptor extends InterceptorOfASingleElement { - - ElementInterceptor(ElementLocator locator, WebDriver driver) { - super(locator, driver); - } - @Override - protected Object getObject(WebElement element, Method method, Object[] args) throws Throwable { - try { - return method.invoke(element, args); - } - catch (Throwable t){ - throw ThrowableUtil.extractReadableException(t); - } - } + ElementInterceptor(ElementLocator locator, WebDriver driver) { + super(locator, driver); + } + + @Override protected Object getObject(WebElement element, Method method, Object[] args) + throws Throwable { + try { + return method.invoke(element, args); + } catch (Throwable t) { + throw ThrowableUtil.extractReadableException(t); + } + } } diff --git a/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java index 35bb4dfd6..062e6a904 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/ElementListInterceptor.java @@ -17,32 +17,29 @@ package io.appium.java_client.pagefactory; import io.appium.java_client.MobileElement; - -import java.lang.reflect.Method; -import java.util.List; import io.appium.java_client.pagefactory.interceptors.InterceptorOfAListOfElements; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.pagefactory.ElementLocator; +import java.lang.reflect.Method; +import java.util.List; + /** - * * Intercepts requests to the list of {@link MobileElement} - * */ -class ElementListInterceptor extends InterceptorOfAListOfElements{ +class ElementListInterceptor extends InterceptorOfAListOfElements { - ElementListInterceptor(ElementLocator locator){ - super(locator); - } + ElementListInterceptor(ElementLocator locator) { + super(locator); + } - @Override - protected Object getObject(List elements, Method method, Object[] args) throws Throwable { - try { - return method.invoke(elements, args); - } - catch (Throwable t){ - throw ThrowableUtil.extractReadableException(t); - } - } + @Override protected Object getObject(List elements, Method method, Object[] args) + throws Throwable { + try { + return method.invoke(elements, args); + } catch (Throwable t) { + throw ThrowableUtil.extractReadableException(t); + } + } } diff --git a/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java b/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java index 44f25da53..700503968 100644 --- a/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java +++ b/src/main/java/io/appium/java_client/pagefactory/OverrideWidget.java @@ -23,47 +23,48 @@ /** * This annotation should mark an abstract/certain Widget object class * or field that declares some abstract/certain Widget object class. - * + *

* io.appium.java_client.pagefactory.Widget is the Appium-specific extension of the * Page Object design pattern. - * + *

* About the Page Object design pattern please read these documents: * - https://code.google.com/p/selenium/wiki/PageObjects * - https://code.google.com/p/selenium/wiki/PageFactory -*/ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface OverrideWidget { + */ +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface OverrideWidget { /** * This property is designed for HTML (browser or web view) content. - * + *

* A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. * * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class html() default Widget.class; + /** * This property is designed for Android native content. - * + *

* A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. * * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class androidUIAutomator() default Widget.class; + /** * This property is designed for iOS native content. - * + *

* A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. * * @return a class which extends {@link io.appium.java_client.pagefactory.Widget} */ Class iOSUIAutomation() default Widget.class; + /** * This property is designed for Android native content when Selendroid automation is used. - * + *

* A declared class should not be abstract. Declared class also should be a subclass * of an annotated class/class which is declared by an annotated field. * diff --git a/src/main/java/io/appium/java_client/pagefactory/OverrideWidgetReader.java b/src/main/java/io/appium/java_client/pagefactory/OverrideWidgetReader.java index c03d66e27..4c3b9eeb2 100644 --- a/src/main/java/io/appium/java_client/pagefactory/OverrideWidgetReader.java +++ b/src/main/java/io/appium/java_client/pagefactory/OverrideWidgetReader.java @@ -17,6 +17,8 @@ import io.appium.java_client.pagefactory.bys.ContentType; +import io.appium.java_client.remote.AutomationName; + import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -24,8 +26,6 @@ import java.util.HashMap; import java.util.Map; -import io.appium.java_client.remote.AutomationName; - import static io.appium.java_client.pagefactory.WidgetConstructorUtil.findConvenientConstructor; import static io.appium.java_client.remote.MobilePlatform.ANDROID; import static io.appium.java_client.remote.MobilePlatform.IOS; @@ -39,26 +39,30 @@ class OverrideWidgetReader { @SuppressWarnings("unchecked") private static Class getConvenientClass(Class declaredClass, - AnnotatedElement annotatedElement, String method) { + AnnotatedElement annotatedElement, String method) { Class convenientClass; OverrideWidget overrideWidget = annotatedElement.getAnnotation(OverrideWidget.class); try { - if (overrideWidget == null || (convenientClass = (Class) OverrideWidget. - class.getDeclaredMethod(method, new Class[]{}).invoke(overrideWidget)).equals(EMPTY)) + if (overrideWidget == null || (convenientClass = + (Class) OverrideWidget.class + .getDeclaredMethod(method, new Class[] {}).invoke(overrideWidget)) + .equals(EMPTY)) convenientClass = declaredClass; - } catch (NoSuchMethodException|InvocationTargetException|IllegalAccessException e) { + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } if (!declaredClass.isAssignableFrom(convenientClass)) { - throw new IllegalArgumentException(new InstantiationException(declaredClass.getName() + " is not assignable from " + + throw new IllegalArgumentException( + new InstantiationException(declaredClass.getName() + " is not assignable from " + convenientClass.getName())); } int modifiers = convenientClass.getModifiers(); if (Modifier.isAbstract(modifiers)) { - throw new IllegalArgumentException(new InstantiationException(convenientClass.getName() + " is abstract so " + + throw new IllegalArgumentException( + new InstantiationException(convenientClass.getName() + " is abstract so " + "it can't be instantiated")); } @@ -66,19 +70,18 @@ private static Class getConvenientClass(Class getDefaultOrHTMLWidgetClass(Class declaredClass, - AnnotatedElement annotatedElement) { + static Class getDefaultOrHTMLWidgetClass( + Class declaredClass, AnnotatedElement annotatedElement) { return getConvenientClass(declaredClass, annotatedElement, HTML); } static Class getMobileNativeWidgetClass(Class declaredClass, - AnnotatedElement annotatedElement, String platform, - String automation) { + AnnotatedElement annotatedElement, String platform, String automation) { String transformedPlatform = platform.toUpperCase().trim(); String transformedAutomation = automation.toUpperCase().trim(); - if (ANDROID.toUpperCase().equals(transformedPlatform) - && AutomationName.SELENDROID.toUpperCase().equals(transformedAutomation)) { + if (ANDROID.toUpperCase().equals(transformedPlatform) && AutomationName.SELENDROID + .toUpperCase().equals(transformedAutomation)) { return getConvenientClass(declaredClass, annotatedElement, SELENDROID); } @@ -93,26 +96,30 @@ static Class getMobileNativeWidgetClass(Class getConstructorOfADefaultOrHTMLWidget(Class declaredClass, - AnnotatedElement annotatedElement) { - Class clazz = getDefaultOrHTMLWidgetClass(declaredClass, annotatedElement); + private static Constructor getConstructorOfADefaultOrHTMLWidget( + Class declaredClass, AnnotatedElement annotatedElement) { + Class clazz = + getDefaultOrHTMLWidgetClass(declaredClass, annotatedElement); return findConvenientConstructor(clazz); } - private static Constructor getConstructorOfAMobileNativeWidgets(Class declaredClass, - AnnotatedElement annotatedElement, - String platform, String automation) { - Class clazz = getMobileNativeWidgetClass(declaredClass, annotatedElement, platform, automation); + private static Constructor getConstructorOfAMobileNativeWidgets( + Class declaredClass, AnnotatedElement annotatedElement, String platform, + String automation) { + Class clazz = + getMobileNativeWidgetClass(declaredClass, annotatedElement, platform, automation); return findConvenientConstructor(clazz); } - static Map> read(Class declaredClass, - AnnotatedElement annotatedElement, - String platform, String automation) { + static Map> read( + Class declaredClass, AnnotatedElement annotatedElement, String platform, + String automation) { Map> result = new HashMap<>(); - result.put(ContentType.HTML_OR_DEFAULT, getConstructorOfADefaultOrHTMLWidget(declaredClass, annotatedElement)); + result.put(ContentType.HTML_OR_DEFAULT, + getConstructorOfADefaultOrHTMLWidget(declaredClass, annotatedElement)); result.put(ContentType.NATIVE_MOBILE_SPECIFIC, - getConstructorOfAMobileNativeWidgets(declaredClass, annotatedElement, platform, automation)); + getConstructorOfAMobileNativeWidgets(declaredClass, annotatedElement, platform, + automation)); return result; } } diff --git a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindAll.java b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindAll.java index a702fda76..cc70fcb80 100644 --- a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindAll.java +++ b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindAll.java @@ -26,8 +26,7 @@ * It will then search for all elements that match any criteria. Note that elements * are not guaranteed to be in document order. */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface SelendroidFindAll { - SelendroidFindBy[] value(); + SelendroidFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBy.java b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBy.java index 5e14c08a4..24d278a17 100644 --- a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBy.java @@ -29,14 +29,19 @@ * this allows users to quickly and easily create PageObjects. * using Selendroid UI selectors like, id, name, class name, tag and xpath */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface SelendroidFindBy { - String id() default ""; - String name() default ""; - String className() default ""; - String tagName() default ""; - String xpath() default ""; - String linkText() default ""; - String partialLinkText() default ""; + String id() default ""; + + String name() default ""; + + String className() default ""; + + String tagName() default ""; + + String xpath() default ""; + + String linkText() default ""; + + String partialLinkText() default ""; } diff --git a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBys.java b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBys.java index 044ecd19e..60c1ee864 100644 --- a/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBys.java +++ b/src/main/java/io/appium/java_client/pagefactory/SelendroidFindBys.java @@ -24,8 +24,7 @@ /** * Used to mark a field on a Page Object to indicate that lookup should use a series of @SelendroidFindBy tags */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface SelendroidFindBys { - SelendroidFindBy[] value(); + SelendroidFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java index bcfb18bf2..410941c62 100644 --- a/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java +++ b/src/main/java/io/appium/java_client/pagefactory/ThrowableUtil.java @@ -33,7 +33,8 @@ static boolean isInvalidSelectorRootCause(Throwable e) { return true; } - if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN) || String.valueOf(e.getMessage()).contains("Locator Strategy \\w+ is not supported")) { + if (String.valueOf(e.getMessage()).contains(INVALID_SELECTOR_PATTERN) || String + .valueOf(e.getMessage()).contains("Locator Strategy \\w+ is not supported")) { return true; } @@ -53,7 +54,8 @@ static boolean isStaleElementReferenceException(Throwable e) { } static Throwable extractReadableException(Throwable e) { - if (!RuntimeException.class.equals(e.getClass()) && !InvocationTargetException.class.equals(e.getClass())) { + if (!RuntimeException.class.equals(e.getClass()) && !InvocationTargetException.class + .equals(e.getClass())) { return e; } diff --git a/src/main/java/io/appium/java_client/pagefactory/TimeOutDuration.java b/src/main/java/io/appium/java_client/pagefactory/TimeOutDuration.java index 1069ff0fc..c329a696c 100644 --- a/src/main/java/io/appium/java_client/pagefactory/TimeOutDuration.java +++ b/src/main/java/io/appium/java_client/pagefactory/TimeOutDuration.java @@ -37,25 +37,25 @@ public TimeOutDuration(long time, TimeUnit unit) { setTime(time, unit); } - public long getTime(){ + public long getTime() { return time; } - public TimeUnit getTimeUnit(){ + public void setTime(TimeUnit newTimeUnit) { + checkNotNull(newTimeUnit); + unit = newTimeUnit; + } + + public TimeUnit getTimeUnit() { return unit; } - public void setTime(long newTime){ + public void setTime(long newTime) { checkArgument(newTime >= 0, "Duration < 0: %d", newTime); time = newTime; } - public void setTime(TimeUnit newTimeUnit){ - checkNotNull(newTimeUnit); - unit = newTimeUnit; - } - - public void setTime(long newTime, TimeUnit newTimeUnit){ + public void setTime(long newTime, TimeUnit newTimeUnit) { setTime(newTime); setTime(newTimeUnit); } diff --git a/src/main/java/io/appium/java_client/pagefactory/Widget.java b/src/main/java/io/appium/java_client/pagefactory/Widget.java index 53ba24211..9a2690af7 100644 --- a/src/main/java/io/appium/java_client/pagefactory/Widget.java +++ b/src/main/java/io/appium/java_client/pagefactory/Widget.java @@ -21,6 +21,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.internal.WrapsElement; + import java.util.List; import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.unpackWebDriverFromSearchContext; @@ -29,7 +30,7 @@ * It is the Appium-specific extension of the Page Object design pattern. It allows user * to create objects which typify some element with nested sub-elements. Also it allows to describe and encapsulate * logic of interaction/behavior within. - * + *

* About the Page Object design pattern please read these documents: * - https://code.google.com/p/selenium/wiki/PageObjects * - https://code.google.com/p/selenium/wiki/PageFactory @@ -42,23 +43,19 @@ protected Widget(WebElement element) { this.element = element; } - @Override - public List findElements(By by) { + @Override public List findElements(By by) { return element.findElements(by); } - @Override - public WebElement findElement(By by) { + @Override public WebElement findElement(By by) { return element.findElement(by); } - @Override - public WebDriver getWrappedDriver() { + @Override public WebDriver getWrappedDriver() { return unpackWebDriverFromSearchContext(element); } - @Override - public WebElement getWrappedElement() { + @Override public WebElement getWrappedElement() { return (WebElement) element; } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/WidgetByBuilder.java index ace46cd91..073efa77d 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetByBuilder.java @@ -17,6 +17,7 @@ package io.appium.java_client.pagefactory; import org.openqa.selenium.By; + import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; @@ -28,11 +29,6 @@ class WidgetByBuilder extends DefaultElementByBuilder { - private enum WhatIsNeeded { - DEFAULT_OR_HTML, - MOBILE_NATIVE - } - protected WidgetByBuilder(String platform, String automation) { super(platform, automation); } @@ -51,8 +47,7 @@ private static Class getClassFromAListField(Field field) { return (Class) listType; } - @SuppressWarnings("unchecked") - private By getByFromDeclaredClass(WhatIsNeeded whatIsNeeded) { + @SuppressWarnings("unchecked") private By getByFromDeclaredClass(WhatIsNeeded whatIsNeeded) { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); Field field = Field.class.cast(annotatedElement); Class declaredClass; @@ -61,61 +56,61 @@ private By getByFromDeclaredClass(WhatIsNeeded whatIsNeeded) { try { if (List.class.isAssignableFrom(field.getType())) { declaredClass = getClassFromAListField(field); - } - else { + } else { declaredClass = field.getType(); } Class convenientClass; if (whatIsNeeded.equals(WhatIsNeeded.DEFAULT_OR_HTML)) { - convenientClass = getDefaultOrHTMLWidgetClass((Class) declaredClass, field); - } - else { - convenientClass = getMobileNativeWidgetClass((Class) declaredClass, field, platform, automation); + convenientClass = + getDefaultOrHTMLWidgetClass((Class) declaredClass, field); + } else { + convenientClass = + getMobileNativeWidgetClass((Class) declaredClass, field, + platform, automation); } while (result == null && !convenientClass.equals(Object.class)) { setAnnotated(convenientClass); if (whatIsNeeded.equals(WhatIsNeeded.DEFAULT_OR_HTML)) { result = super.buildDefaultBy(); - } - else { + } else { result = super.buildMobileNativeBy(); } convenientClass = convenientClass.getSuperclass(); } return result; - } - finally { + } finally { if (field != null) { setAnnotated(field); } } } - @Override - protected By buildDefaultBy() { + @Override protected By buildDefaultBy() { By defaultBy = super.buildDefaultBy(); if (defaultBy != null) { return defaultBy; - } - else { + } else { return getByFromDeclaredClass(WhatIsNeeded.DEFAULT_OR_HTML); } } - @Override - protected By buildMobileNativeBy() { + @Override protected By buildMobileNativeBy() { By mobileBy = super.buildMobileNativeBy(); if (mobileBy != null) { return mobileBy; - } - else { + } else { return getByFromDeclaredClass(WhatIsNeeded.MOBILE_NATIVE); } } + + private enum WhatIsNeeded { + DEFAULT_OR_HTML, + MOBILE_NATIVE + } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetConstructorUtil.java b/src/main/java/io/appium/java_client/pagefactory/WidgetConstructorUtil.java index e5b90a80e..542ce9fc3 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetConstructorUtil.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetConstructorUtil.java @@ -29,9 +29,9 @@ private WidgetConstructorUtil() { @SuppressWarnings("unchecked") static Constructor findConvenientConstructor(Class clazz) { Constructor[] constructors = clazz.getDeclaredConstructors(); - for (Constructor constructor: constructors) { + for (Constructor constructor : constructors) { Class[] params = constructor.getParameterTypes(); - if (constructor.getParameterTypes().length !=1) { + if (constructor.getParameterTypes().length != 1) { continue; } @@ -42,8 +42,10 @@ static Constructor findConvenientConstructor(Class> declared = Arrays.asList(clazz.getDeclaredConstructors()); - throw new NoSuchMethodError(clazz.getName() + " has no convenient constructor which could pass a " + - WebElement.class.getName() + " instance as a parameter. The actual list of constructors: " + + throw new NoSuchMethodError( + clazz.getName() + " has no convenient constructor which could pass a " + + WebElement.class.getName() + + " instance as a parameter. The actual list of constructors: " + declared.toString()); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java index d1846c722..870e60e29 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetInterceptor.java @@ -30,16 +30,16 @@ import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; -class WidgetInterceptor extends InterceptorOfASingleElement{ +class WidgetInterceptor extends InterceptorOfASingleElement { - private WebElement cachedElement; private final Map> instantiationMap; private final Map cachedInstances = new HashMap<>(); private final TimeOutDuration duration; + private WebElement cachedElement; WidgetInterceptor(CacheableLocator locator, WebDriver driver, WebElement cachedElement, - Map> instantiationMap, - TimeOutDuration duration) { + Map> instantiationMap, + TimeOutDuration duration) { super(locator, driver); this.cachedElement = cachedElement; this.instantiationMap = instantiationMap; @@ -47,11 +47,12 @@ class WidgetInterceptor extends InterceptorOfASingleElement{ } - @Override - protected Object getObject(WebElement element, Method method, Object[] args) throws Throwable { + @Override protected Object getObject(WebElement element, Method method, Object[] args) + throws Throwable { ContentType type = getCurrentContentType(element); - if (cachedElement == null || (locator !=null && !((CacheableLocator) locator).isLookUpCached()) || - cachedInstances.size() == 0) { + if (cachedElement == null || (locator != null && !((CacheableLocator) locator) + .isLookUpCached()) || + cachedInstances.size() == 0) { cachedElement = element; Widget widget = instantiationMap.get(type).newInstance(cachedElement); cachedInstances.put(type, widget); @@ -59,14 +60,13 @@ protected Object getObject(WebElement element, Method method, Object[] args) thr } try { return method.invoke(cachedInstances.get(type), args); - } - catch (Throwable t) { + } catch (Throwable t) { throw ThrowableUtil.extractReadableException(t); } } - public Object intercept(Object obj, Method method, Object[] args, - MethodProxy proxy) throws Throwable { + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) + throws Throwable { if (locator != null) { return super.intercept(obj, method, args, proxy); } diff --git a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java index 833956a45..872e4d68b 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java +++ b/src/main/java/io/appium/java_client/pagefactory/WidgetListInterceptor.java @@ -21,6 +21,7 @@ import io.appium.java_client.pagefactory.utils.ProxyFactory; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; + import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; @@ -29,17 +30,18 @@ import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; -class WidgetListInterceptor extends InterceptorOfAListOfElements{ +class WidgetListInterceptor extends InterceptorOfAListOfElements { private final Map> instantiationMap; - private List cachedElements; private final List cachedWidgets = new ArrayList<>(); private final Class declaredType; private final TimeOutDuration duration; private final WebDriver driver; + private List cachedElements; - WidgetListInterceptor(CacheableLocator locator, WebDriver driver, Map> instantiationMap, - Class declaredType, TimeOutDuration duration) { + WidgetListInterceptor(CacheableLocator locator, WebDriver driver, + Map> instantiationMap, + Class declaredType, TimeOutDuration duration) { super(locator); this.instantiationMap = instantiationMap; this.declaredType = declaredType; @@ -48,23 +50,25 @@ class WidgetListInterceptor extends InterceptorOfAListOfElements{ } - @Override - protected Object getObject(List elements, Method method, Object[] args) throws Throwable { - if (cachedElements == null || (locator !=null && !((CacheableLocator) locator).isLookUpCached())) { + @Override protected Object getObject(List elements, Method method, Object[] args) + throws Throwable { + if (cachedElements == null || (locator != null && !((CacheableLocator) locator) + .isLookUpCached())) { cachedElements = elements; cachedWidgets.clear(); - for (WebElement element: cachedElements) { + for (WebElement element : cachedElements) { ContentType type = getCurrentContentType(element); - Class[] params = new Class[] {instantiationMap.get(type).getParameterTypes()[0]}; - cachedWidgets.add(ProxyFactory.getEnhancedProxy(declaredType, params, new Object[]{element}, + Class[] params = + new Class[] {instantiationMap.get(type).getParameterTypes()[0]}; + cachedWidgets.add(ProxyFactory + .getEnhancedProxy(declaredType, params, new Object[] {element}, new WidgetInterceptor(null, driver, element, instantiationMap, duration))); } } try { return method.invoke(cachedWidgets, args); - } - catch (Throwable t) { + } catch (Throwable t) { throw ThrowableUtil.extractReadableException(t); } } diff --git a/src/main/java/io/appium/java_client/pagefactory/WithTimeout.java b/src/main/java/io/appium/java_client/pagefactory/WithTimeout.java index 6f1995564..6746ea8e6 100644 --- a/src/main/java/io/appium/java_client/pagefactory/WithTimeout.java +++ b/src/main/java/io/appium/java_client/pagefactory/WithTimeout.java @@ -23,13 +23,12 @@ import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) /** This annotation is used when some element waits for time that differs from defined by default - */ -public @interface WithTimeout { + */ public @interface WithTimeout { long time(); + TimeUnit unit(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java b/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java index 9eaa2bae1..c4f75baca 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/ContentMappedBy.java @@ -16,37 +16,36 @@ package io.appium.java_client.pagefactory.bys; +import org.openqa.selenium.By; +import org.openqa.selenium.SearchContext; +import org.openqa.selenium.WebElement; + import java.util.List; - import java.util.Map; +import java.util.Map; - import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.*; - import org.openqa.selenium.By; - import org.openqa.selenium.SearchContext; - import org.openqa.selenium.WebElement; +import static io.appium.java_client.pagefactory.utils.WebDriverUnpackUtility.getCurrentContentType; public class ContentMappedBy extends By { - private final Map map; private final static String NATIVE_APP_PATTERN = "NATIVE_APP"; + private final Map map; public ContentMappedBy(Map map) { - this.map = map; - } + this.map = map; + } - @Override - public List findElements(SearchContext context) { + @Override public List findElements(SearchContext context) { return context.findElements(map.get(getCurrentContentType(context))); } - @Override - public String toString(){ + @Override public String toString() { By defaultBy = map.get(ContentType.HTML_OR_DEFAULT); - By nativeBy = map.get(ContentType.NATIVE_MOBILE_SPECIFIC); + By nativeBy = map.get(ContentType.NATIVE_MOBILE_SPECIFIC); if (defaultBy.equals(nativeBy)) return defaultBy.toString(); - return "Locator map: " + "\n" + - "- native content: \"" + nativeBy.toString() + "\" \n" + - "- html content: \"" + defaultBy.toString() + "\""; + return "Locator map: " + "\n" + + "- native content: \"" + nativeBy.toString() + "\" \n" + + "- html content: \"" + defaultBy.toString() + "\""; } } diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/ContentType.java b/src/main/java/io/appium/java_client/pagefactory/bys/ContentType.java index 68a5371cb..c22160b4a 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/ContentType.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/ContentType.java @@ -17,6 +17,6 @@ package io.appium.java_client.pagefactory.bys; public enum ContentType { - HTML_OR_DEFAULT, - NATIVE_MOBILE_SPECIFIC; + HTML_OR_DEFAULT, + NATIVE_MOBILE_SPECIFIC; } diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java index 5602331a7..d6c4bb41d 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/builder/AppiumByBuilder.java @@ -14,13 +14,17 @@ * limitations under the License. */ package io.appium.java_client.pagefactory.bys.builder; + import org.openqa.selenium.By; import org.openqa.selenium.support.pagefactory.AbstractAnnotations; import org.openqa.selenium.support.pagefactory.ByAll; import org.openqa.selenium.support.pagefactory.ByChained; import java.lang.annotation.Annotation; -import java.lang.reflect.*; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -37,18 +41,29 @@ public abstract class AppiumByBuilder extends AbstractAnnotations { final static Class[] DEFAULT_ANNOTATION_METHOD_ARGUMENTS = new Class[] {}; - private final static List METHODS_TO_BE_EXCLUDED_WHEN_ANNOTATION_IS_READ = new ArrayList() { - private static final long serialVersionUID = 1L; - { - List objectClassMethodNames = getMethodNames(Object.class - .getDeclaredMethods()); - addAll(objectClassMethodNames); - List annotationClassMethodNames = getMethodNames(Annotation.class - .getDeclaredMethods()); - annotationClassMethodNames.removeAll(objectClassMethodNames); - addAll(annotationClassMethodNames); - } - }; + private final static List METHODS_TO_BE_EXCLUDED_WHEN_ANNOTATION_IS_READ = + new ArrayList() { + private static final long serialVersionUID = 1L; + + { + List objectClassMethodNames = + getMethodNames(Object.class.getDeclaredMethods()); + addAll(objectClassMethodNames); + List annotationClassMethodNames = + getMethodNames(Annotation.class.getDeclaredMethods()); + annotationClassMethodNames.removeAll(objectClassMethodNames); + addAll(annotationClassMethodNames); + } + }; + protected final AnnotatedElementContainer annotatedElementContainer; + protected final String platform; + protected final String automation; + + protected AppiumByBuilder(String platform, String automation) { + this.annotatedElementContainer = new AnnotatedElementContainer(); + this.platform = String.valueOf(platform).toUpperCase().trim(); + this.automation = String.valueOf(automation).toUpperCase().trim(); + } private static List getMethodNames(Method[] methods) { List names = new ArrayList<>(); @@ -58,18 +73,15 @@ private static List getMethodNames(Method[] methods) { return names; } - private static Method[] prepareAnnotationMethods( - Class annotation) { - List targeAnnotationMethodNamesList = getMethodNames(annotation - .getDeclaredMethods()); - targeAnnotationMethodNamesList - .removeAll(METHODS_TO_BE_EXCLUDED_WHEN_ANNOTATION_IS_READ); + private static Method[] prepareAnnotationMethods(Class annotation) { + List targeAnnotationMethodNamesList = + getMethodNames(annotation.getDeclaredMethods()); + targeAnnotationMethodNamesList.removeAll(METHODS_TO_BE_EXCLUDED_WHEN_ANNOTATION_IS_READ); Method[] result = new Method[targeAnnotationMethodNamesList.size()]; for (String methodName : targeAnnotationMethodNamesList) { try { - result[targeAnnotationMethodNamesList.indexOf(methodName)] = annotation - .getMethod(methodName, - DEFAULT_ANNOTATION_METHOD_ARGUMENTS); + result[targeAnnotationMethodNamesList.indexOf(methodName)] = + annotation.getMethod(methodName, DEFAULT_ANNOTATION_METHOD_ARGUMENTS); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } @@ -81,8 +93,7 @@ private static String getFilledValue(Annotation mobileBy) { Method[] values = prepareAnnotationMethods(mobileBy.getClass()); for (Method value : values) { try { - String strategyParameter = value.invoke(mobileBy, - new Object[] {}).toString(); + String strategyParameter = value.invoke(mobileBy, new Object[] {}).toString(); if (!"".equals(strategyParameter)) { return value.getName(); } @@ -90,9 +101,9 @@ private static String getFilledValue(Annotation mobileBy) { throw new RuntimeException(e); } } - throw new IllegalArgumentException("@" - + mobileBy.getClass().getSimpleName() + ": one of " - + Strategies.strategiesNames().toString() + " should be filled"); + throw new IllegalArgumentException( + "@" + mobileBy.getClass().getSimpleName() + ": one of " + Strategies.strategiesNames() + .toString() + " should be filled"); } private static By getMobileBy(Annotation annotation, String valueName) { @@ -102,22 +113,21 @@ private static By getMobileBy(Annotation annotation, String valueName) { return strategy.getBy(annotation); } } - throw new IllegalArgumentException("@" - + annotation.getClass().getSimpleName() - + ": There is an unknown strategy " + valueName); + throw new IllegalArgumentException( + "@" + annotation.getClass().getSimpleName() + ": There is an unknown strategy " + + valueName); } @SuppressWarnings("unchecked") private static T getComplexMobileBy(Annotation[] annotations, - Class requiredByClass) { + Class requiredByClass) { By[] byArray = new By[annotations.length]; for (int i = 0; i < annotations.length; i++) { - byArray[i] = getMobileBy(annotations[i], - getFilledValue(annotations[i])); + byArray[i] = getMobileBy(annotations[i], getFilledValue(annotations[i])); } try { Constructor c = requiredByClass.getConstructor(By[].class); - Object[] values = new Object[] { byArray }; + Object[] values = new Object[] {byArray}; return (T) c.newInstance(values); } catch (Exception e) { throw new RuntimeException(e); @@ -129,7 +139,7 @@ protected static By createBy(Annotation[] annotations, HowToUseSelectors howToUs return null; } - switch (howToUseLocators ) { + switch (howToUseLocators) { case USE_ONE: { return getMobileBy(annotations[0], getFilledValue(annotations[0])); } @@ -145,23 +155,13 @@ protected static By createBy(Annotation[] annotations, HowToUseSelectors howToUs } } - protected final AnnotatedElementContainer annotatedElementContainer; - protected final String platform; - protected final String automation; - - protected AppiumByBuilder(String platform, String automation) { - this.annotatedElementContainer = new AnnotatedElementContainer(); - this.platform = String.valueOf(platform).toUpperCase().trim(); - this.automation = String.valueOf(automation).toUpperCase().trim(); - } - /** * This method should be used for the setting up of * AnnotatedElement instances before the building of * By-locator strategies * - * @param annotated is an instance of class which type extends - * {@link java.lang.reflect.AnnotatedElement} + * @param annotated is an instance of class which type extends + * {@link java.lang.reflect.AnnotatedElement} */ public void setAnnotated(AnnotatedElement annotated) { this.annotatedElementContainer.setAnnotated(annotated); diff --git a/src/main/java/io/appium/java_client/pagefactory/bys/builder/Strategies.java b/src/main/java/io/appium/java_client/pagefactory/bys/builder/Strategies.java index ca3a80dde..3c81a2019 100644 --- a/src/main/java/io/appium/java_client/pagefactory/bys/builder/Strategies.java +++ b/src/main/java/io/appium/java_client/pagefactory/bys/builder/Strategies.java @@ -28,8 +28,7 @@ */ enum Strategies { BYUIAUTOMATOR("uiAutomator") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { String value = getValue(annotation, this); if (annotation.annotationType().equals(AndroidFindBy.class)) { return MobileBy.AndroidUIAutomator(value); @@ -41,60 +40,48 @@ By getBy(Annotation annotation) { } }, BYACCESSABILITY("accessibility") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return MobileBy.AccessibilityId(getValue(annotation, this)); } }, BYCLASSNAME("className") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.className(getValue(annotation, this)); } }, BYID("id") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.id(getValue(annotation, this)); } }, BYTAG("tagName") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.tagName(getValue(annotation, this)); } }, BYNAME("name") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.name(getValue(annotation, this)); } }, BYXPATH("xpath") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.xpath(getValue(annotation, this)); } }, BYLINKTEXT("linkText") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.linkText(getValue(annotation, this)); } }, BYPARTIALLINKTEXT("partialLinkText") { - @Override - By getBy(Annotation annotation) { + @Override By getBy(Annotation annotation) { return By.partialLinkText(getValue(annotation, this)); } }; private final String valueName; - String returnValueName() { - return valueName; - } - Strategies(String valueName) { this.valueName = valueName; } @@ -110,17 +97,20 @@ static List strategiesNames() { return result; } - private static String getValue(Annotation annotation, - Strategies strategy) { + private static String getValue(Annotation annotation, Strategies strategy) { try { - Method m = annotation.getClass().getMethod(strategy.valueName, - AppiumByBuilder.DEFAULT_ANNOTATION_METHOD_ARGUMENTS); + Method m = annotation.getClass() + .getMethod(strategy.valueName, AppiumByBuilder.DEFAULT_ANNOTATION_METHOD_ARGUMENTS); return m.invoke(annotation, new Object[] {}).toString(); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } + String returnValueName() { + return valueName; + } + By getBy(Annotation annotation) { return null; } diff --git a/src/main/java/io/appium/java_client/pagefactory/iOSFindAll.java b/src/main/java/io/appium/java_client/pagefactory/iOSFindAll.java index 1a1444f2c..9c307279d 100644 --- a/src/main/java/io/appium/java_client/pagefactory/iOSFindAll.java +++ b/src/main/java/io/appium/java_client/pagefactory/iOSFindAll.java @@ -26,8 +26,7 @@ * It will then search for all elements that match any criteria. Note that elements * are not guaranteed to be in document order. */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface iOSFindAll { - iOSFindBy[] value(); + iOSFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java index 6f38ed2a5..c38794886 100644 --- a/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java +++ b/src/main/java/io/appium/java_client/pagefactory/iOSFindBy.java @@ -29,18 +29,24 @@ * this allows users to quickly and easily create PageObjects. * using iOS UI selectors, accessibility, id, name, class name, tag and xpath */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface iOSFindBy { - String uiAutomator() default ""; - String accessibility() default ""; - String id() default ""; - @Deprecated - /** - * By.name selector is not supported by Appium server node since 1.5.x. - * So this option is going to be removed further. Be careful. - */String name() default ""; - String className() default ""; - String tagName() default ""; - String xpath() default ""; + String uiAutomator() default ""; + + String accessibility() default ""; + + String id() default ""; + + @Deprecated + /** + * By.name selector is not supported by Appium server node since 1.5.x. + * So this option is going to be removed further. Be careful. + */ + String name() default ""; + + String className() default ""; + + String tagName() default ""; + + String xpath() default ""; } diff --git a/src/main/java/io/appium/java_client/pagefactory/iOSFindBys.java b/src/main/java/io/appium/java_client/pagefactory/iOSFindBys.java index d673d2ba0..eff68d55d 100644 --- a/src/main/java/io/appium/java_client/pagefactory/iOSFindBys.java +++ b/src/main/java/io/appium/java_client/pagefactory/iOSFindBys.java @@ -24,8 +24,7 @@ /** * Used to mark a field on a Page Object to indicate that lookup should use a series of @iOSFindBy tags */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface iOSFindBys { - iOSFindBy[] value(); + iOSFindBy[] value(); } diff --git a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfAListOfElements.java b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfAListOfElements.java index 1fc25a09e..76fd9d909 100644 --- a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfAListOfElements.java +++ b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfAListOfElements.java @@ -32,11 +32,12 @@ public InterceptorOfAListOfElements(ElementLocator locator) { this.locator = locator; } - protected abstract Object getObject(List elements, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException, InstantiationException, Throwable; + protected abstract Object getObject(List elements, Method method, Object[] args) + throws InvocationTargetException, IllegalAccessException, InstantiationException, Throwable; - public Object intercept(Object obj, Method method, Object[] args, - MethodProxy proxy) throws Throwable { - if(Object.class.equals(method.getDeclaringClass())) { + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) + throws Throwable { + if (Object.class.equals(method.getDeclaringClass())) { return proxy.invokeSuper(obj, args); } diff --git a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java index 1791a0b57..816ae46e0 100644 --- a/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java +++ b/src/main/java/io/appium/java_client/pagefactory/interceptors/InterceptorOfASingleElement.java @@ -35,16 +35,17 @@ public InterceptorOfASingleElement(ElementLocator locator, WebDriver driver) { this.driver = driver; } - protected abstract Object getObject(WebElement element, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException, InstantiationException, Throwable; + protected abstract Object getObject(WebElement element, Method method, Object[] args) + throws InvocationTargetException, IllegalAccessException, InstantiationException, Throwable; - public Object intercept(Object obj, Method method, Object[] args, - MethodProxy proxy) throws Throwable { - if(Object.class.equals(method.getDeclaringClass())) { + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) + throws Throwable { + if (Object.class.equals(method.getDeclaringClass())) { return proxy.invokeSuper(obj, args); } - if (WrapsDriver.class.isAssignableFrom(method.getDeclaringClass()) && - method.getName().equals("getWrappedDriver")) { + if (WrapsDriver.class.isAssignableFrom(method.getDeclaringClass()) && method.getName() + .equals("getWrappedDriver")) { return driver; } diff --git a/src/main/java/io/appium/java_client/pagefactory/utils/ProxyFactory.java b/src/main/java/io/appium/java_client/pagefactory/utils/ProxyFactory.java index 450d01432..31bebc90c 100644 --- a/src/main/java/io/appium/java_client/pagefactory/utils/ProxyFactory.java +++ b/src/main/java/io/appium/java_client/pagefactory/utils/ProxyFactory.java @@ -21,7 +21,7 @@ import net.sf.cglib.proxy.MethodInterceptor; /** - * Original class is a super class of a + * Original class is a super class of a * proxy object here */ public final class ProxyFactory { @@ -30,13 +30,13 @@ private ProxyFactory() { super(); } - public static T getEnhancedProxy(Class requiredClazz, MethodInterceptor interceptor){ + public static T getEnhancedProxy(Class requiredClazz, MethodInterceptor interceptor) { return getEnhancedProxy(requiredClazz, new Class[] {}, new Object[] {}, interceptor); } @SuppressWarnings("unchecked") public static T getEnhancedProxy(Class requiredClazz, Class[] params, Object[] values, - MethodInterceptor interceptor){ + MethodInterceptor interceptor) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(requiredClazz); enhancer.setCallback(interceptor); diff --git a/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java b/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java index c43aa880e..65696fcf6 100644 --- a/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java +++ b/src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java @@ -31,27 +31,26 @@ public final class WebDriverUnpackUtility { private final static String NATIVE_APP_PATTERN = "NATIVE_APP"; - public static WebDriver unpackWebDriverFromSearchContext( - SearchContext searchContext) { + public static WebDriver unpackWebDriverFromSearchContext(SearchContext searchContext) { WebDriver driver = null; if (searchContext instanceof WebDriver) return (WebDriver) searchContext; if (searchContext instanceof WrapsDriver) - return unpackWebDriverFromSearchContext(((WrapsDriver) searchContext) - .getWrappedDriver()); + return unpackWebDriverFromSearchContext( + ((WrapsDriver) searchContext).getWrappedDriver()); // Search context it is not only Webdriver. Webelement is search context // too. // RemoteWebElement and MobileElement implement WrapsDriver if (searchContext instanceof WrapsElement) - return unpackWebDriverFromSearchContext(((WrapsElement) searchContext) - .getWrappedElement()); + return unpackWebDriverFromSearchContext( + ((WrapsElement) searchContext).getWrappedElement()); return driver; } - public static String getPlatform(WebDriver driver){ + public static String getPlatform(WebDriver driver) { if (driver == null) return null; @@ -67,25 +66,25 @@ public static String getPlatform(WebDriver driver){ //to detect platform if (HasCapabilities.class.isAssignableFrom(driverClass)) return String.valueOf(((HasCapabilities) driver).getCapabilities(). - getCapability(MobileCapabilityType.PLATFORM_NAME)); + getCapability(MobileCapabilityType.PLATFORM_NAME)); return null; } - public static String getAutomation(WebDriver driver){ + public static String getAutomation(WebDriver driver) { if (driver == null) return null; if (HasCapabilities.class.isAssignableFrom(driver.getClass())) return String.valueOf(((HasCapabilities) driver).getCapabilities(). - getCapability(MobileCapabilityType.AUTOMATION_NAME)); + getCapability(MobileCapabilityType.AUTOMATION_NAME)); return null; } - public static ContentType getCurrentContentType(SearchContext context){ + public static ContentType getCurrentContentType(SearchContext context) { WebDriver driver = WebDriverUnpackUtility.unpackWebDriverFromSearchContext(context); - if (!ContextAware.class.isAssignableFrom(driver.getClass())){ //it is desktop browser + if (!ContextAware.class.isAssignableFrom(driver.getClass())) { //it is desktop browser return ContentType.HTML_OR_DEFAULT; } diff --git a/src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java b/src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java index 524940827..3c0827e90 100644 --- a/src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java +++ b/src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java @@ -205,5 +205,5 @@ public interface AndroidMobileCapabilityType extends CapabilityType { */ String RECREATE_CHROME_DRIVER_SESSIONS = "recreateChromeDriverSessions"; - String SELENDROID_PORT = "selendroidPort"; + String SELENDROID_PORT = "selendroidPort"; } diff --git a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java index c54e3a659..4755660f4 100644 --- a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java +++ b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java @@ -21,44 +21,41 @@ import org.openqa.selenium.WebDriverException; import org.openqa.selenium.remote.*; import org.openqa.selenium.remote.http.HttpClient; +import org.openqa.selenium.remote.internal.ApacheHttpClient; import org.openqa.selenium.remote.service.DriverService; import java.io.IOException; import java.net.ConnectException; import java.net.URL; import java.util.Map; -import org.openqa.selenium.remote.internal.ApacheHttpClient; -public class AppiumCommandExecutor extends HttpCommandExecutor{ +public class AppiumCommandExecutor extends HttpCommandExecutor { private final DriverService service; public AppiumCommandExecutor(Map additionalCommands, - URL addressOfRemoteServer, - HttpClient.Factory httpClientFactory) { + URL addressOfRemoteServer, HttpClient.Factory httpClientFactory) { super(additionalCommands, addressOfRemoteServer, httpClientFactory); service = null; } - - public AppiumCommandExecutor(Map additionalCommands, - DriverService service, - HttpClient.Factory httpClientFactory) { + + public AppiumCommandExecutor(Map additionalCommands, DriverService service, + HttpClient.Factory httpClientFactory) { super(additionalCommands, service.getUrl(), httpClientFactory); this.service = service; } - - public AppiumCommandExecutor(Map additionalCommands, - URL addressOfRemoteServer) { + + public AppiumCommandExecutor(Map additionalCommands, + URL addressOfRemoteServer) { this(additionalCommands, addressOfRemoteServer, new ApacheHttpClient.Factory()); } - public AppiumCommandExecutor(Map additionalCommands, - DriverService service) { + public AppiumCommandExecutor(Map additionalCommands, + DriverService service) { this(additionalCommands, service, new ApacheHttpClient.Factory()); } - @Override - public Response execute(Command command) throws IOException, WebDriverException { + @Override public Response execute(Command command) throws IOException, WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) { service.start(); } @@ -68,7 +65,7 @@ public Response execute(Command command) throws IOException, WebDriverException } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && - rootCause.getMessage().contains("Connection refused") && service != null){ + rootCause.getMessage().contains("Connection refused") && service != null) { if (service.isRunning()) throw new WebDriverException("The session is closed!", t); diff --git a/src/main/java/io/appium/java_client/remote/HideKeyboardStrategy.java b/src/main/java/io/appium/java_client/remote/HideKeyboardStrategy.java index ba5c1e8ef..eb4be26ae 100644 --- a/src/main/java/io/appium/java_client/remote/HideKeyboardStrategy.java +++ b/src/main/java/io/appium/java_client/remote/HideKeyboardStrategy.java @@ -18,6 +18,6 @@ public interface HideKeyboardStrategy { - String TAP_OUTSIDE = "tapOutside"; - String PRESS_KEY = "pressKey"; -} \ No newline at end of file + String TAP_OUTSIDE = "tapOutside"; + String PRESS_KEY = "pressKey"; +} diff --git a/src/main/java/io/appium/java_client/remote/MobileBrowserType.java b/src/main/java/io/appium/java_client/remote/MobileBrowserType.java index 5a52a5d12..9ca3c79ed 100644 --- a/src/main/java/io/appium/java_client/remote/MobileBrowserType.java +++ b/src/main/java/io/appium/java_client/remote/MobileBrowserType.java @@ -18,8 +18,8 @@ public interface MobileBrowserType { - String SAFARI = "Safari"; - String BROWSER = "Browser"; - String CHROMIUM = "Chromium"; - String CHROME = "Chrome"; + String SAFARI = "Safari"; + String BROWSER = "Browser"; + String CHROMIUM = "Chromium"; + String CHROME = "Chrome"; } diff --git a/src/main/java/io/appium/java_client/remote/MobileCapabilityType.java b/src/main/java/io/appium/java_client/remote/MobileCapabilityType.java index 2266a6760..a51e99157 100644 --- a/src/main/java/io/appium/java_client/remote/MobileCapabilityType.java +++ b/src/main/java/io/appium/java_client/remote/MobileCapabilityType.java @@ -24,138 +24,130 @@ */ public interface MobileCapabilityType extends CapabilityType { - /** - * Which automation engine to use - */ - String AUTOMATION_NAME = "automationName"; - - /** - * Which mobile OS platform to use - */ - String PLATFORM_NAME = "platformName"; - - /** - * Mobile OS version - */ - String PLATFORM_VERSION = "platformVersion"; - - /** - * The kind of mobile device or emulator to use - */ - String DEVICE_NAME = "deviceName"; - - /** - * How long (in seconds) Appium will wait for a new command from the - * client before assuming the client quit and ending the session - */ - String NEW_COMMAND_TIMEOUT = "newCommandTimeout"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#DEVICE_READY_TIMEOUT} - */ - @Deprecated - String DEVICE_READY_TIMEOUT = "deviceReadyTimeout"; - - /** - * Deprecated. Moved to {@link IOSMobileCapabilityType#LAUNCH_TIMEOUT} - */ - @Deprecated - String LAUNCH_TIMEOUT = "launchTimeout"; - - /** - * The absolute local path or remote http URL to an .ipa or .apk file, or a .zip containing one of these. - * Appium will attempt to install this app binary on the appropriate device first. - * Note that this capability is not required for Android if you specify appPackage and appActivity - * capabilities (see below). Incompatible with browserName. - */ - String APP = "app"; - - /** - * Name of mobile web browser to automate. Should be an empty string if automating an app instead. - */ - String BROWSER_NAME = "browserName"; - - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_PACKAGE} - */ - @Deprecated - String APP_PACKAGE = "appPackage"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_ACTIVITY} - */ - @Deprecated - String APP_ACTIVITY = "appActivity"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_WAIT_ACTIVITY} - */ - @Deprecated - String APP_WAIT_ACTIVITY = "appWaitActivity"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_WAIT_PACKAGE} - */ - @Deprecated - String APP_WAIT_PACKAGE = "appWaitPackage"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#DONT_STOP_APP_ON_RESET} - */ - @Deprecated - String DONT_STOP_APP_ON_RESET = "dontStopAppOnReset"; - - /** - * Unique device identifier of the connected physical device - */ - String UDID = "udid"; - - /** - * Sauce-specific - */ - String APPIUM_VERSION = "appiumVersion"; - - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#UNICODE_KEYBOARD} - */ - @Deprecated - String UNICODE_KEYBOARD = "unicodeKeyboard"; - - /** - * (Sim/Emu-only) Language to set for the simulator / emulator - */ - String LANGUAGE = "language"; - - /** - * (Sim/Emu-only) Locale to set for the simulator / emulator - */ - String LOCALE = "locale"; - - /** - * (Sim/Emu-only) start in a certain orientation - */ - String ORIENTATION = "orientation"; - - /** - * Move directly into Webview context. Default false - */ - String AUTO_WEBVIEW = "autoWebview"; - - /** - * Don't reset app state before this session. Default false - */ - String NO_RESET = "noReset"; - - /** - * (iOS) Delete the entire simulator folder. (Android) Reset app state by uninstalling app instead of clearing app data. - * On Android, this will also remove the app after the session is complete. Default false - */ - String FULL_RESET = "fullReset"; - - @Deprecated - /** - * Deprecated. Moved to {@link AndroidMobileCapabilityType#SELENDROID_PORT} - */ - String SELENDROID_PORT = "selendroidPort"; + /** + * Which automation engine to use + */ + String AUTOMATION_NAME = "automationName"; + + /** + * Which mobile OS platform to use + */ + String PLATFORM_NAME = "platformName"; + + /** + * Mobile OS version + */ + String PLATFORM_VERSION = "platformVersion"; + + /** + * The kind of mobile device or emulator to use + */ + String DEVICE_NAME = "deviceName"; + + /** + * How long (in seconds) Appium will wait for a new command from the + * client before assuming the client quit and ending the session + */ + String NEW_COMMAND_TIMEOUT = "newCommandTimeout"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#DEVICE_READY_TIMEOUT} + */ + @Deprecated String DEVICE_READY_TIMEOUT = "deviceReadyTimeout"; + + /** + * Deprecated. Moved to {@link IOSMobileCapabilityType#LAUNCH_TIMEOUT} + */ + @Deprecated String LAUNCH_TIMEOUT = "launchTimeout"; + + /** + * The absolute local path or remote http URL to an .ipa or .apk file, or a .zip containing one of these. + * Appium will attempt to install this app binary on the appropriate device first. + * Note that this capability is not required for Android if you specify appPackage and appActivity + * capabilities (see below). Incompatible with browserName. + */ + String APP = "app"; + + /** + * Name of mobile web browser to automate. Should be an empty string if automating an app instead. + */ + String BROWSER_NAME = "browserName"; + + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_PACKAGE} + */ + @Deprecated String APP_PACKAGE = "appPackage"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_ACTIVITY} + */ + @Deprecated String APP_ACTIVITY = "appActivity"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_WAIT_ACTIVITY} + */ + @Deprecated String APP_WAIT_ACTIVITY = "appWaitActivity"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#APP_WAIT_PACKAGE} + */ + @Deprecated String APP_WAIT_PACKAGE = "appWaitPackage"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#DONT_STOP_APP_ON_RESET} + */ + @Deprecated String DONT_STOP_APP_ON_RESET = "dontStopAppOnReset"; + + /** + * Unique device identifier of the connected physical device + */ + String UDID = "udid"; + + /** + * Sauce-specific + */ + String APPIUM_VERSION = "appiumVersion"; + + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#UNICODE_KEYBOARD} + */ + @Deprecated String UNICODE_KEYBOARD = "unicodeKeyboard"; + + /** + * (Sim/Emu-only) Language to set for the simulator / emulator + */ + String LANGUAGE = "language"; + + /** + * (Sim/Emu-only) Locale to set for the simulator / emulator + */ + String LOCALE = "locale"; + + /** + * (Sim/Emu-only) start in a certain orientation + */ + String ORIENTATION = "orientation"; + + /** + * Move directly into Webview context. Default false + */ + String AUTO_WEBVIEW = "autoWebview"; + + /** + * Don't reset app state before this session. Default false + */ + String NO_RESET = "noReset"; + + /** + * (iOS) Delete the entire simulator folder. (Android) Reset app state by uninstalling app instead of clearing app data. + * On Android, this will also remove the app after the session is complete. Default false + */ + String FULL_RESET = "fullReset"; + + @Deprecated + /** + * Deprecated. Moved to {@link AndroidMobileCapabilityType#SELENDROID_PORT} + */ + String SELENDROID_PORT = "selendroidPort"; } diff --git a/src/main/java/io/appium/java_client/remote/MobilePlatform.java b/src/main/java/io/appium/java_client/remote/MobilePlatform.java index 533e158bd..0db586b0d 100644 --- a/src/main/java/io/appium/java_client/remote/MobilePlatform.java +++ b/src/main/java/io/appium/java_client/remote/MobilePlatform.java @@ -18,7 +18,7 @@ public interface MobilePlatform { - String ANDROID = "Android"; - String IOS = "iOS"; - String FIREFOX_OS = "FirefoxOS"; + String ANDROID = "Android"; + String IOS = "iOS"; + String FIREFOX_OS = "FirefoxOS"; } diff --git a/src/main/java/io/appium/java_client/service/local/AppiumDriverLocalService.java b/src/main/java/io/appium/java_client/service/local/AppiumDriverLocalService.java index 01ba8c639..6d8025525 100644 --- a/src/main/java/io/appium/java_client/service/local/AppiumDriverLocalService.java +++ b/src/main/java/io/appium/java_client/service/local/AppiumDriverLocalService.java @@ -52,10 +52,8 @@ public final class AppiumDriverLocalService extends DriverService { private CommandLine process = null; AppiumDriverLocalService(String ipAddress, File nodeJSExec, int nodeJSPort, - ImmutableList nodeJSArgs, - ImmutableMap nodeJSEnvironment, - long startupTimeout, - TimeUnit timeUnit) throws IOException { + ImmutableList nodeJSArgs, ImmutableMap nodeJSEnvironment, + long startupTimeout, TimeUnit timeUnit) throws IOException { super(nodeJSExec, nodeJSPort, nodeJSArgs, nodeJSEnvironment); this.ipAddress = ipAddress; this.nodeJSExec = nodeJSExec; @@ -66,21 +64,26 @@ public final class AppiumDriverLocalService extends DriverService { this.timeUnit = timeUnit; } + public static AppiumDriverLocalService buildDefaultService() { + return buildService(new AppiumServiceBuilder()); + } + + public static AppiumDriverLocalService buildService(AppiumServiceBuilder builder) { + return builder.build(); + } + /** * @return The base URL for the managed appium server. */ - @Override - public URL getUrl() { + @Override public URL getUrl() { try { - return new URL(String.format(URL_MASK, ipAddress, - nodeJSPort)); + return new URL(String.format(URL_MASK, ipAddress, nodeJSPort)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } - @Override - public boolean isRunning() { + @Override public boolean isRunning() { lock.lock(); try { if (process == null) { @@ -103,18 +106,20 @@ public boolean isRunning() { } - private void ping(long time, TimeUnit timeUnit) throws UrlChecker.TimeoutException{ + private void ping(long time, TimeUnit timeUnit) throws UrlChecker.TimeoutException { URL url = getUrl(); try { URL status = new URL(url.toString() + "/status"); new UrlChecker().waitUntilAvailable(time, timeUnit, status); } catch (MalformedURLException e) { - throw new RuntimeException("There is something wrong with the URL " + url.toString().toString() + "/status"); + throw new RuntimeException( + "There is something wrong with the URL " + url.toString().toString() + "/status"); } } /** * Starts the defined appium server + * * @throws AppiumServerHasNotBeenStartedLocallyException If an error occurs while spawning the child process. * @see #stop() */ @@ -126,7 +131,8 @@ public void start() throws AppiumServerHasNotBeenStartedLocallyException { } try { - process = new CommandLine(this.nodeJSExec.getCanonicalPath(), nodeJSArgs.toArray(new String[]{})); + process = new CommandLine(this.nodeJSExec.getCanonicalPath(), + nodeJSArgs.toArray(new String[] {})); process.setEnvironmentVariables(nodeJSEnvironment); process.copyOutputTo(stream); process.executeAsync(); @@ -134,15 +140,15 @@ public void start() throws AppiumServerHasNotBeenStartedLocallyException { } catch (Throwable e) { destroyProcess(); String msgTxt = "The local appium server has not been started. " + - "The given Node.js executable: " + this.nodeJSExec.getAbsolutePath() + " Arguments: " + nodeJSArgs.toString() + " " + "\n"; + "The given Node.js executable: " + this.nodeJSExec.getAbsolutePath() + + " Arguments: " + nodeJSArgs.toString() + " " + "\n"; if (process != null) { String processStream = process.getStdOut(); if (!StringUtils.isBlank(processStream)) msgTxt = msgTxt + "Process output: " + processStream + "\n"; } - throw new AppiumServerHasNotBeenStartedLocallyException(msgTxt, - e); + throw new AppiumServerHasNotBeenStartedLocallyException(msgTxt, e); } } finally { lock.unlock(); @@ -155,22 +161,19 @@ public void start() throws AppiumServerHasNotBeenStartedLocallyException { * * @see #start() */ - @Override - public void stop() { + @Override public void stop() { lock.lock(); try { if (process != null) { destroyProcess(); } process = null; - } - finally { + } finally { lock.unlock(); } } - - private void destroyProcess(){ + private void destroyProcess() { if (process.isRunning()) { process.destroy(); } @@ -187,24 +190,16 @@ public String getStdOut() { return null; } - public void addOutPutStream(OutputStream outputStream){ + public void addOutPutStream(OutputStream outputStream) { checkNotNull(outputStream, "outputStream parameter is NULL!"); stream.add(outputStream); } - public void addOutPutStreams(List outputStreams){ + public void addOutPutStreams(List outputStreams) { checkNotNull(outputStreams, "outputStreams parameter is NULL!"); - for (OutputStream stream: outputStreams){ + for (OutputStream stream : outputStreams) { addOutPutStream(stream); } } - public static AppiumDriverLocalService buildDefaultService(){ - return buildService(new AppiumServiceBuilder()); - } - - public static AppiumDriverLocalService buildService(AppiumServiceBuilder builder){ - return builder.build(); - } - } diff --git a/src/main/java/io/appium/java_client/service/local/AppiumServerHasNotBeenStartedLocallyException.java b/src/main/java/io/appium/java_client/service/local/AppiumServerHasNotBeenStartedLocallyException.java index 2a637a9ef..d8d84aca3 100644 --- a/src/main/java/io/appium/java_client/service/local/AppiumServerHasNotBeenStartedLocallyException.java +++ b/src/main/java/io/appium/java_client/service/local/AppiumServerHasNotBeenStartedLocallyException.java @@ -17,13 +17,13 @@ package io.appium.java_client.service.local; -public class AppiumServerHasNotBeenStartedLocallyException extends RuntimeException{ +public class AppiumServerHasNotBeenStartedLocallyException extends RuntimeException { - public AppiumServerHasNotBeenStartedLocallyException(String messege, Throwable t){ + public AppiumServerHasNotBeenStartedLocallyException(String messege, Throwable t) { super(messege, t); } - public AppiumServerHasNotBeenStartedLocallyException(String messege){ + public AppiumServerHasNotBeenStartedLocallyException(String messege) { super(messege); } } diff --git a/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java b/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java index 72e1e629a..f03653550 100644 --- a/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java +++ b/src/main/java/io/appium/java_client/service/local/AppiumServiceBuilder.java @@ -29,7 +29,8 @@ import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.service.DriverService; -import java.io.*; +import java.io.File; +import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; @@ -37,7 +38,8 @@ import static com.google.common.base.Preconditions.checkNotNull; -public final class AppiumServiceBuilder extends DriverService.Builder { +public final class AppiumServiceBuilder + extends DriverService.Builder { /** * The environmental variable used to define @@ -52,7 +54,7 @@ public final class AppiumServiceBuilder extends DriverService.Builder PATH_CAPABILITIES = new ArrayList() { { add(AndroidMobileCapabilityType.KEYSTORE_PATH); @@ -60,26 +62,21 @@ public final class AppiumServiceBuilder extends DriverService.Builder 0, "Time value should be greater than zero", time); this.startupTimeout = time; @@ -287,9 +290,8 @@ public AppiumServiceBuilder withStartUpTimeOut(long time, TimeUnit timeUnit){ return this; } - - void checkAppiumJS(){ - if (appiumJS != null){ + void checkAppiumJS() { + if (appiumJS != null) { validateNodeStructure(appiumJS); return; } @@ -298,17 +300,16 @@ void checkAppiumJS(){ if (StringUtils.isBlank(appiumJS)) { appiumJS = System.getenv(APPIUM_PATH); } - if (!StringUtils.isBlank(appiumJS)){ + if (!StringUtils.isBlank(appiumJS)) { File node = new File(appiumJS); validateNodeStructure(node); - this.appiumJS = node; + this.appiumJS = node; return; } this.appiumJS = findNodeInCurrentFileSystem(); } - private String parseCapabilitiesIfWindows() { String result = StringUtils.EMPTY; @@ -326,8 +327,7 @@ private String parseCapabilitiesIfWindows() { if (String.class.isAssignableFrom(value.getClass())) { if (PATH_CAPABILITIES.contains(entry.getKey())) { value = "\\\"" + String.valueOf(value).replace("\\", "/") + "\\\""; - } - else { + } else { value = "\\\"" + String.valueOf(value) + "\\\""; } } else { @@ -378,16 +378,14 @@ private String parseCapabilitiesIfUNIX() { return "{" + result + "}"; } - @SuppressWarnings("unchecked") - private String parseCapabilities() { + @SuppressWarnings("unchecked") private String parseCapabilities() { if (Platform.getCurrent().is(Platform.WINDOWS)) { return parseCapabilitiesIfWindows(); } return parseCapabilitiesIfUNIX(); } - @Override - protected ImmutableList createArgs() { + @Override protected ImmutableList createArgs() { List argList = new ArrayList<>(); checkAppiumJS(); argList.add(appiumJS.getAbsolutePath()); @@ -396,18 +394,18 @@ protected ImmutableList createArgs() { if (StringUtils.isBlank(ipAddress)) { ipAddress = DEFAULT_LOCAL_IP_ADDRESS; - } - else { + } else { InetAddressValidator validator = InetAddressValidator.getInstance(); if (!validator.isValid(ipAddress) && !validator.isValidInet4Address(ipAddress) && - !validator.isValidInet6Address(ipAddress)) - throw new IllegalArgumentException("The invalid IP address " + ipAddress + " is defined"); + !validator.isValidInet6Address(ipAddress)) + throw new IllegalArgumentException( + "The invalid IP address " + ipAddress + " is defined"); } argList.add("--address"); argList.add(ipAddress); File log = getLogFile(); - if (log != null){ + if (log != null) { argList.add("--log"); argList.add(log.getAbsolutePath()); } @@ -466,11 +464,10 @@ public AppiumServiceBuilder usingAnyFreePort() { * Defines the environment for the launched appium server. * * @param environment A map of the environment variables to launch the - * appium server with. + * appium server with. * @return A self reference. */ - @Override - public AppiumServiceBuilder withEnvironment(Map environment) { + @Override public AppiumServiceBuilder withEnvironment(Map environment) { return super.withEnvironment(environment); } @@ -485,29 +482,19 @@ public AppiumServiceBuilder withLogFile(File logFile) { } @Override - protected AppiumDriverLocalService createDriverService(File nodeJSExecutable, int nodeJSPort, ImmutableList nodeArguments, - ImmutableMap nodeEnvironment) { + protected AppiumDriverLocalService createDriverService(File nodeJSExecutable, int nodeJSPort, + ImmutableList nodeArguments, ImmutableMap nodeEnvironment) { try { - return new AppiumDriverLocalService(ipAddress, nodeJSExecutable, nodeJSPort, nodeArguments, nodeEnvironment, - startupTimeout, timeUnit); + return new AppiumDriverLocalService(ipAddress, nodeJSExecutable, nodeJSPort, + nodeArguments, nodeEnvironment, startupTimeout, timeUnit); } catch (IOException e) { throw new RuntimeException(e); } } - private static void disposeCachedFile(File file) { - if (file != null) { - try { - FileUtils.forceDelete(file); - } catch (IOException ignored) { - } - } - } - - @Override - protected void finalize() throws Throwable { + @Override protected void finalize() throws Throwable { disposeCachedFile(npmScript); disposeCachedFile(getNodeJSExecutable); super.finalize(); } -} \ No newline at end of file +} diff --git a/src/main/java/io/appium/java_client/service/local/InvalidNodeJSInstance.java b/src/main/java/io/appium/java_client/service/local/InvalidNodeJSInstance.java index c38734fdd..929f077d5 100644 --- a/src/main/java/io/appium/java_client/service/local/InvalidNodeJSInstance.java +++ b/src/main/java/io/appium/java_client/service/local/InvalidNodeJSInstance.java @@ -16,8 +16,8 @@ package io.appium.java_client.service.local; -public class InvalidNodeJSInstance extends RuntimeException{ - public InvalidNodeJSInstance(String message, Throwable t){ +public class InvalidNodeJSInstance extends RuntimeException { + public InvalidNodeJSInstance(String message, Throwable t) { super(message, t); } } diff --git a/src/main/java/io/appium/java_client/service/local/InvalidServerInstanceException.java b/src/main/java/io/appium/java_client/service/local/InvalidServerInstanceException.java index b8b54fa71..f7c1fe337 100644 --- a/src/main/java/io/appium/java_client/service/local/InvalidServerInstanceException.java +++ b/src/main/java/io/appium/java_client/service/local/InvalidServerInstanceException.java @@ -21,7 +21,7 @@ public class InvalidServerInstanceException extends RuntimeException { private static String MESSAGE_PREFIX = "Invalid server instance exception has occured: "; - public InvalidServerInstanceException(String messege, Throwable t){ + public InvalidServerInstanceException(String messege, Throwable t) { super(MESSAGE_PREFIX + messege, t); } } diff --git a/src/main/java/io/appium/java_client/service/local/ListOutputStream.java b/src/main/java/io/appium/java_client/service/local/ListOutputStream.java index c48c5285a..c0d83cef4 100644 --- a/src/main/java/io/appium/java_client/service/local/ListOutputStream.java +++ b/src/main/java/io/appium/java_client/service/local/ListOutputStream.java @@ -31,35 +31,32 @@ ListOutputStream add(OutputStream stream) { return this; } - @Override - public void write(int i) throws IOException { - for (OutputStream stream: streams) { + @Override public void write(int i) throws IOException { + for (OutputStream stream : streams) { stream.write(i); } } - @Override - public void write(byte[] var1) throws IOException { - for (OutputStream stream: streams) { + @Override public void write(byte[] var1) throws IOException { + for (OutputStream stream : streams) { stream.write(var1, 0, var1.length); } } - @Override - public void write(byte[] var1, int var2, int var3) throws IOException { - for (OutputStream stream: streams) { + @Override public void write(byte[] var1, int var2, int var3) throws IOException { + for (OutputStream stream : streams) { stream.write(var1, var2, var3); } } public void flush() throws IOException { - for (OutputStream stream: streams) { + for (OutputStream stream : streams) { stream.flush(); } } public void close() throws IOException { - for (OutputStream stream: streams) { + for (OutputStream stream : streams) { stream.close(); } } diff --git a/src/main/java/io/appium/java_client/service/local/Scripts.java b/src/main/java/io/appium/java_client/service/local/Scripts.java index 21376eea6..02f1c84e2 100644 --- a/src/main/java/io/appium/java_client/service/local/Scripts.java +++ b/src/main/java/io/appium/java_client/service/local/Scripts.java @@ -17,12 +17,12 @@ package io.appium.java_client.service.local; import org.apache.commons.io.IOUtils; + import java.io.*; enum Scripts { GET_PATH_TO_DEFAULT_NODE_UNIX("get_path_to_default_node.sh"), - GET_NODE_JS_EXECUTABLE("getExe.js") - ; + GET_NODE_JS_EXECUTABLE("getExe.js"); private static final String RESOURCE_FOLDER = "/scripts/"; private final String script; @@ -39,7 +39,7 @@ public File getScriptFile() { throw new RuntimeException(e); } - String[] splittedName = this.script.split("\\."); + String[] splittedName = this.script.split("\\."); File scriptFile; try { scriptFile = File.createTempFile(splittedName[0], "." + splittedName[1]); diff --git a/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java index ec6b80462..d5e3b9802 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/AndroidServerFlag.java @@ -17,9 +17,9 @@ package io.appium.java_client.service.local.flags; /** -* Here is the list of Android specific server arguments. -*/ -public enum AndroidServerFlag implements ServerArgument{ + * Here is the list of Android specific server arguments. + */ +public enum AndroidServerFlag implements ServerArgument { /** * Port to use on device to talk to Appium. Sample: * --bootstrap-port 4724 @@ -28,81 +28,73 @@ public enum AndroidServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Java package of the Android app you want to run (e.g., * com.example.android.MyApp). Sample: * --app-pkg com.example.android.MyApp */ - @Deprecated - PACKAGE("--app-pkg"), + @Deprecated PACKAGE("--app-pkg"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Activity name for the Android activity you want to launch * from your package (e.g., MainActivity). Sample: * --app-activity MainActivity */ - @Deprecated - ACTIVITY("--app-activity"), + @Deprecated ACTIVITY("--app-activity"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Package name for the Android activity you want to wait for * (e.g., com.example.android.MyApp). Sample: * --app-wait-package com.example.android.MyApp */ - @Deprecated - APP_WAIT_PACKAGE("--app-wait-package"), + @Deprecated APP_WAIT_PACKAGE("--app-wait-package"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Activity name for the Android activity you want to wait * for (e.g., SplashActivity). Sample: * --app-wait-activity SplashActivity */ - @Deprecated - APP_WAIT_ACTIVITY("--app-wait-activity"), + @Deprecated APP_WAIT_ACTIVITY("--app-wait-activity"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Fully qualified instrumentation class. * Passed to -w in adb shell am instrument -e coverage true -w. Sample: * --android-coverage com.my.Pkg/com.my.Pkg.instrumentation.MyInstrumentation */ - @Deprecated - ANDROID_COVERAGE("--android-coverage"), + @Deprecated ANDROID_COVERAGE("--android-coverage"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Name of the avd to launch. Sample: * --avd @default */ - @Deprecated - AVD("--avd"), + @Deprecated AVD("--avd"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Additional emulator arguments to launch the avd. Sample: * --avd-args -no-snapshot-load */ - @Deprecated - AVD_ARGS("--avd-args"), + @Deprecated AVD_ARGS("--avd-args"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Timeout in seconds while waiting for device to become * ready. Sample: * --device-ready-timeout 5 */ - @Deprecated - DEVICE_READY_TIMEOUT("--device-ready-timeout"), + @Deprecated DEVICE_READY_TIMEOUT("--device-ready-timeout"), /** * Local port used for communication with Selendroid. Sample: * --selendroid-port 8080 @@ -111,90 +103,80 @@ public enum AndroidServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* When set the keystore will be used to sign apks. Default: false */ - @Deprecated - USE_KEY_STORE("--use-keystore"), + @Deprecated USE_KEY_STORE("--use-keystore"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Path to keystore. Sample: * --keystore-path /Users/user/.android/debug.keystore */ - @Deprecated - KEY_STORE_PATH("--keystore-path"), + @Deprecated KEY_STORE_PATH("--keystore-path"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Password to keystore. Default: android */ - @Deprecated - KEY_STORE_PASSWORD("--keystore-password"), + @Deprecated KEY_STORE_PASSWORD("--keystore-password"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Key alias. Default: androiddebugkey */ - @Deprecated - KEY_ALIAS("--key-alias"), + @Deprecated KEY_ALIAS("--key-alias"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Key password. Default: android */ - @Deprecated - KEY_PASSWORD("--key-password"), + @Deprecated KEY_PASSWORD("--key-password"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Intent action which will be used to start activity. Default: * android.intent.action.MAIN. Sample: --intent-action android.intent.action.MAIN */ - @Deprecated - INTENT_ACTION("--intent-action"), + @Deprecated INTENT_ACTION("--intent-action"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Intent category which will be used to start activity. Default: android.intent.category.LAUNCHER. * Sample:s --intent-category android.intent.category.APP_CONTACTS */ - @Deprecated - INTENT_CATEGORY("--intent-category"), + @Deprecated INTENT_CATEGORY("--intent-category"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Flags that will be used to start activity. Default: 0x10200000. * Sample: --intent-flags 0x10200000 */ - @Deprecated - INTENT_FLAGS("--intent-flags"), + @Deprecated INTENT_FLAGS("--intent-flags"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Additional intent arguments that will be used to start * activity. Default: null. * Sample: --intent-args 0x10200000 */ - @Deprecated - INTENT_ARGUMENTS("--intent-args"), + @Deprecated INTENT_ARGUMENTS("--intent-args"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* When included, refrains from stopping the app before * restart. Default: false */ - @Deprecated - DO_NOT_STOP_APP_ON_RESET("--dont-stop-app-on-reset"), + @Deprecated DO_NOT_STOP_APP_ON_RESET("--dont-stop-app-on-reset"), /** * If set, prevents Appium from killing the adb server * instance. Default: false @@ -216,8 +198,7 @@ public enum AndroidServerFlag implements ServerArgument{ this.arg = arg; } - @Override - public String getArgument() { + @Override public String getArgument() { return arg; } } diff --git a/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java index cfbfeaf15..ac8d5db0d 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/GeneralServerFlag.java @@ -20,7 +20,7 @@ /** * Here is the list of common Appium server arguments. */ -public enum GeneralServerFlag implements ServerArgument{ +public enum GeneralServerFlag implements ServerArgument { /** * Enter REPL mode */ @@ -34,17 +34,16 @@ public enum GeneralServerFlag implements ServerArgument{ * IOS: abs path to simulator-compiled .app file or the bundle_id of the desired target on device; Android: abs path to .apk file. * Sample: --app /abs/path/to/my.app */ - APP("--app"), + APP("--app"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Unique device identifier of the connected physical device. * Sample: * --udid 1adsf-sdfas-asdf-123sdf */ - @Deprecated - UIID("--udid"), + @Deprecated UIID("--udid"), /** * callback IP Address (default: same as address). * Sample: --callback-address 127.0.0.1 @@ -62,12 +61,11 @@ public enum GeneralServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Don’t reset app state between sessions (IOS: don’t delete app plist files; Android: don’t uninstall app before new session). * Default: false */ - @Deprecated - NO_RESET("--no-reset"), + @Deprecated NO_RESET("--no-reset"), /** * Pre-launch the application before allowing the first session (Requires –app and, for Android, –app-pkg and –app-activity). * Default: false @@ -101,61 +99,54 @@ public enum GeneralServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Name of the mobile device to use. * Sample: --device-name iPhone Retina (4-inch), Android Emulator */ - @Deprecated - DEVICE_NAME("--device-name"), + @Deprecated DEVICE_NAME("--device-name"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Name of the mobile platform: iOS, Android, or FirefoxOS * Sample: --platform-name iOS */ - @Deprecated - PLATFORM_NAME("--platform-name"), + @Deprecated PLATFORM_NAME("--platform-name"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Version of the mobile platform. Sample: --platform-version 7.1 */ - @Deprecated - PLATFORM_VERSION("--platform-version"), + @Deprecated PLATFORM_VERSION("--platform-version"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Name of the automation tool: Appium or Selendroid. Sample: --automation-name Appium */ - @Deprecated - AUTOMATION_NAME("--automation-name"), + @Deprecated AUTOMATION_NAME("--automation-name"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Name of the mobile browser: Safari or Chrome. Sample: --browser-name Safari */ - @Deprecated - BROWSER_NAME("--browser-name"), + @Deprecated BROWSER_NAME("--browser-name"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Language for the iOS simulator / Android Emulator. Sample: --language en */ - @Deprecated - LANGUAGE("--language"), + @Deprecated LANGUAGE("--language"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Locale for the iOS simulator / Android Emulator. Sample: --locale en_US */ - @Deprecated - LOCALE("--locale"), + @Deprecated LOCALE("--locale"), /** * Configuration JSON file to register Appium with selenium grid. Sample: * --nodeconfig /abs/path/to/nodeconfig.json @@ -177,7 +168,7 @@ public enum GeneralServerFlag implements ServerArgument{ * * Port upon which ChromeDriver will run. Sample: --chromedriver-port 9515 */ - CHROME_DRIVER_PORT("--chromedriver-port"), + CHROME_DRIVER_PORT("--chromedriver-port"), @Deprecated /** * This flag IS deprecated because it is moved to @@ -185,7 +176,7 @@ public enum GeneralServerFlag implements ServerArgument{ * * ChromeDriver executable full path */ - CHROME_DRIVER_EXECUTABLE("--chromedriver-executable"), + CHROME_DRIVER_EXECUTABLE("--chromedriver-executable"), /** * Show info about the Appium server configuration and exit. Default: false */ @@ -193,16 +184,15 @@ public enum GeneralServerFlag implements ServerArgument{ /** * Bypass Appium’s checks to ensure we can read/write necessary files. Default: false */ - NO_PERMS_CHECKS( "--no-perms-check"), + NO_PERMS_CHECKS("--no-perms-check"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* The default command timeout for the server to use for all sessions. Will * still be overridden by newCommandTimeout cap. Default: 60 */ - @Deprecated - COMMAND_TIMEOUT("--command-timeout"), + @Deprecated COMMAND_TIMEOUT("--command-timeout"), /** * Cause sessions to fail if desired caps are sent in that Appium does not * recognize as valid for the selected device. Default: false @@ -221,7 +211,7 @@ public enum GeneralServerFlag implements ServerArgument{ /** * Add long stack traces to log entries. Recommended for debugging only. - * + *

* Default: false */ ASYNC_TRACE("--async-trace"); @@ -232,8 +222,7 @@ public enum GeneralServerFlag implements ServerArgument{ this.arg = arg; } - @Override - public String getArgument() { + @Override public String getArgument() { return arg; } } diff --git a/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java b/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java index 733013038..383cb97dd 100644 --- a/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java +++ b/src/main/java/io/appium/java_client/service/local/flags/IOSServerFlag.java @@ -17,18 +17,17 @@ package io.appium.java_client.service.local.flags; /** -* Here is the list of iOS specific server arguments. -*/ -public enum IOSServerFlag implements ServerArgument{ + * Here is the list of iOS specific server arguments. + */ +public enum IOSServerFlag implements ServerArgument { /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* the relative path of the dir where Localizable.strings file * resides. Default: en.lproj. Sample: --localizable-strings-dir en.lproj */ - @Deprecated - LOCALIZABLE_STRING_PATH("--localizable-strings-dir"), + @Deprecated LOCALIZABLE_STRING_PATH("--localizable-strings-dir"), /** * absolute path to compiled .ipa file. Sample: --ipa /abs/path/to/my.ipa */ @@ -41,20 +40,18 @@ public enum IOSServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * - * how long in ms to wait for Instruments to launch. Default: 90000 + *

+ * how long in ms to wait for Instruments to launch. Default: 90000 */ - @Deprecated - LAUNCH_TIMEOUT("--launch-timeout"), + @Deprecated LAUNCH_TIMEOUT("--launch-timeout"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* IOS has a weird built-in unavoidable delay. We patch this in * appium. If you do not want it patched, pass in this flag. Default: false */ - @Deprecated - USE_NATIVE_INSTRUMENTS("--native-instruments-lib"), + @Deprecated USE_NATIVE_INSTRUMENTS("--native-instruments-lib"), /** * Use the safari app. Default: false */ @@ -62,7 +59,6 @@ public enum IOSServerFlag implements ServerArgument{ /** * use the default simulator that instruments launches * on its own. Default: false - * */ DEFAULT_DEVICE("--default-device"), /** @@ -76,22 +72,20 @@ public enum IOSServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Calendar format for the iOS simulator. * Default: null * Sample: --calendar-format gregorian */ - @Deprecated - CALENDAR_FORMAT("--calendar-format"), + @Deprecated CALENDAR_FORMAT("--calendar-format"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* use LANDSCAPE or PORTRAIT to initialize all requests to this * orientation. Sample: --orientation LANDSCAPE */ - @Deprecated - ORIENTATION("--orientation"), + @Deprecated ORIENTATION("--orientation"), /** * .tracetemplate file to use with Instruments. Sample: --tracetemplate /Users/me/Automation.tracetemplate */ @@ -103,28 +97,25 @@ public enum IOSServerFlag implements ServerArgument{ /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* if set, the iOS simulator log will be written to the console. Default: false */ - @Deprecated - SHOW_SIMULATOR_LOG("--show-sim-log"), + @Deprecated SHOW_SIMULATOR_LOG("--show-sim-log"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* if set, the iOS system log will be written to the console. Default: false */ - @Deprecated - SHOW_IOS_LOG("--show-ios-log"), + @Deprecated SHOW_IOS_LOG("--show-ios-log"), /** * This flag IS deprecated since appium node 1.5.x. It will be removed in the next release. * Be careful. - * + *

* Whether to keep keychains (Library/Keychains) when reset app * between sessions. Default: false */ - @Deprecated - KEEP_KEYCHAINS("--keep-keychains"), + @Deprecated KEEP_KEYCHAINS("--keep-keychains"), /** * Xcode 6 has a bug on some platforms where a certain simulator can only be * launched without error if all other simulator devices are first deleted. @@ -142,9 +133,9 @@ public enum IOSServerFlag implements ServerArgument{ /** * Local port used for communication with ios-webkit-debug-proxy - * + *

* Default value: 27753 - * + *

* Sample: --webkit-debug-proxy-port 27753 */ WEBKIT_DEBUG_PROXY_PORT("--webkit-debug-proxy-port"); @@ -155,8 +146,7 @@ public enum IOSServerFlag implements ServerArgument{ this.arg = arg; } - @Override - public String getArgument() { + @Override public String getArgument() { return arg; } } diff --git a/src/test/java/io/appium/java_client/RottenTomatoesPageSnapshot.html b/src/test/java/io/appium/java_client/RottenTomatoesPageSnapshot.html index 235d1a382..e64e03732 100644 --- a/src/test/java/io/appium/java_client/RottenTomatoesPageSnapshot.html +++ b/src/test/java/io/appium/java_client/RottenTomatoesPageSnapshot.html @@ -1,11 +1,68 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Spectre (2015) - Rotten Tomatoes + + + + + + + + + + + + + + + + + + + + + + + + +

+ + + + + + + + + + + +
+
+
+
+ + +
+
+
+
+
+
+ + + +
+ + + + + +
+ +
+
+
+
+

Spectre (2015)

+ +
+
+ +
+
+
+

Spectre (2015) +

+ +
+ +
+

TOMATOMETER

AUDIENCE SCORE

Critic Consensus: Spectre nudges Daniel Craig's rebooted Bond closer to the glorious, action-driven spectacle of earlier entries, although it's admittedly reliant on established 007 formula.

+
+
+ +
+
+ +
+
+
+ +

TOMATOMETER +

+ +
+
+ +
+
+
+ + +
+
+ +
+
+
+ +
+
+
+ + +
+
+ +
+
+
+
+

AUDIENCE SCORE +

+ + + +
+

Critic Consensus: Spectre + nudges Daniel Craig's rebooted Bond closer to the glorious, action-driven + spectacle of earlier entries, although it's admittedly reliant on + established 007 formula.

+
+
+
+

Tickets & Showtimes

There are no showtimes for this theater.

Enter your location to see where Spectre is playing near you
+ +
+ + +
+

Tickets & Showtimes

+ +
+
+
There are no showtimes for this theater.
+
+ +
Enter your location to see where Spectre is playing near you +
+
+
+ +
+
+ +
+
+
+
+ +
+
+
+ +
+
+
+
+ + + +
+ +
+
+ + + +"event","Footer","Mobile Apps","click")}); + + + + + + + + - + + + + + +
- - - - - - - -
- - +"#showtimes .clickForMore a",function(){ga("gtmTracker.send","event","MOB Modules","Showtimes","View All Theaters")});768>a(window).width()&&(a(document).on("mousedown","#newTrailerModal .closeBtn",function(){ga("gtmTracker.send","event","MOB Modules","link","Mobile - Go back")}),a(document).on("mousedown","#newTrailerModal .moreTrailer",function(){ga("gtmTracker.send","event","MOB Modules","link","Mobile - More Trailers")}))}); + + + + + + + +
+ + + + + + + +
+
+ +
+
+ - -
- -
+ -
+
+ + +
+ + + + + + + + + + + + + + + +
+
+
+
+
+
+
+
+
+
+ -
+
4.4.7Status:Inactive
\ No newline at end of file + +
+ +
+
+ + 4.4.7Status:Inactive
+
+
+ + diff --git a/src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html b/src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html index 8eecabc75..4062d004b 100644 --- a/src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html +++ b/src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html @@ -1,11 +1,64 @@ - + + + + + + + + + + + + + + + + + + + + Top Movies - Opening in Theaters | Rotten Tomatoes + + + + + Top Movies - Opening in Theaters | Rotten Tomatoes + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+
+
+
+
+
+ + + +
+ + + + + +
+ +
+
+
+
+
+
+ +
+
+
+
+
+
-
- -

Spectre

-
+
+
+ + +
+
+ +
+ + +
+ +
+ + +
- + + + +
- + + +
+
- +
- +
- + +
- + +
+ +
+
+
+
+ +
+
+ Spotlight + +
+ + + 96% + + + + + 93% + +
+
+ + Mark Ruffalo, + + Michael Keaton + +
+ +
R, 2 hr. 7 min.
+ +
+
+
Critics Consensus: - Spotlight gracefully handles the lurid details of its fact-based story while resisting the temptation to lionize its heroes, resulting in a drama that - - ... + Spotlight gracefully handles the lurid details of its fact-based + story while resisting the temptation to lionize its heroes, + resulting in a drama that + + ... honors the audience as well as its real-life subjects. - More... - -
- +
+
- - -
- - - Play Trailer - +
+
- - -
-
-
+
+ +
+ +
+ + + +
+ +
+
+ + +"event","Footer","Mobile Apps","click")}); + + + + - + + +
- +"Mobile Header","Menu","Facebook")});a(document).on("mousedown","#navMenu .icon-twitter",function(){ga("gtmTracker.send","event","Mobile Header","Menu","Twitter")})}); + + + + +
+ +
+
+ +
+
+ - + -
- -
+ +
+
+ + +
+ + + + - +
4.4.7Status:Active
\ No newline at end of file + +
+ + + diff --git a/src/test/java/io/appium/java_client/android/AndroidAccessibilityTest.java b/src/test/java/io/appium/java_client/android/AndroidAccessibilityTest.java index 138dd9926..0a9b3826a 100644 --- a/src/test/java/io/appium/java_client/android/AndroidAccessibilityTest.java +++ b/src/test/java/io/appium/java_client/android/AndroidAccessibilityTest.java @@ -16,78 +16,71 @@ package io.appium.java_client.android; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; import io.appium.java_client.MobileElement; import io.appium.java_client.remote.MobileCapabilityType; +import io.appium.java_client.service.local.AppiumDriverLocalService; +import org.junit.*; +import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.util.List; -import io.appium.java_client.service.local.AppiumDriverLocalService; -import org.junit.*; -import org.openqa.selenium.remote.DesiredCapabilities; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class AndroidAccessibilityTest { - - private AppiumDriver driver; + private static AppiumDriverLocalService service; + private AppiumDriver driver; - @BeforeClass - public static void beforeClass() throws Exception{ + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { if (service == null || !service.isRunning()) throw new RuntimeException("An appium server node is not started!"); - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "ApiDemos-debug.apk"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new AndroidDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - @Test - public void findElementsTest() { - List elements = driver.findElementsByAccessibilityId("Accessibility"); - assertTrue(elements.size() > 0); - } - - @Test - public void findElementTest() { + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "ApiDemos-debug.apk"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new AndroidDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + @Test public void findElementsTest() { + List elements = driver.findElementsByAccessibilityId("Accessibility"); + assertTrue(elements.size() > 0); + } + + @Test public void findElementTest() { //WebElement element = - MobileElement element = driver.findElementByAccessibilityId("Accessibility"); - assertNotNull(element); - } - - @Test - public void MobileElementByTest() { - MobileElement element = driver.findElement(MobileBy.AccessibilityId("Accessibility")); - assertNotNull(element); - } - - @Test - public void MobileElementsByTest() { - List elements = driver.findElements(MobileBy.AccessibilityId("Accessibility")); - assertTrue(elements.size() > 0); - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); + MobileElement element = driver.findElementByAccessibilityId("Accessibility"); + assertNotNull(element); + } + + @Test public void MobileElementByTest() { + MobileElement element = driver.findElement(MobileBy.AccessibilityId("Accessibility")); + assertNotNull(element); + } + + @Test public void MobileElementsByTest() { + List elements = + driver.findElements(MobileBy.AccessibilityId("Accessibility")); + assertTrue(elements.size() > 0); } } diff --git a/src/test/java/io/appium/java_client/android/AndroidContextTest.java b/src/test/java/io/appium/java_client/android/AndroidContextTest.java index 88cdca384..15ff09ea8 100644 --- a/src/test/java/io/appium/java_client/android/AndroidContextTest.java +++ b/src/test/java/io/appium/java_client/android/AndroidContextTest.java @@ -16,12 +16,12 @@ package io.appium.java_client.android; -import io.appium.java_client.AppiumDriver; import io.appium.java_client.NoSuchContextException; -import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; @@ -34,64 +34,58 @@ */ public class AndroidContextTest { - private static AndroidDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "ApiDemos-debug.apk"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120); - driver = new AndroidDriver(service.getUrl(), capabilities); - driver.startActivity("io.appium.android.apis", ".view.WebView1"); - Thread.sleep(20000); - } - - @AfterClass - public static void tearDown() throws Exception { - if (driver != null) { - driver.quit(); + private static AndroidDriver driver; + private static AppiumDriverLocalService service; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "ApiDemos-debug.apk"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120); + driver = new AndroidDriver(service.getUrl(), capabilities); + driver.startActivity("io.appium.android.apis", ".view.WebView1"); + Thread.sleep(20000); } - if (service.isRunning()) { - service.stop(); + @AfterClass public static void tearDown() throws Exception { + if (driver != null) { + driver.quit(); + } + + if (service.isRunning()) { + service.stop(); + } + } + + @Test public void testGetContext() { + assertEquals("NATIVE_APP", driver.getContext()); + } + + @Test public void testGetContextHandles() { + assertEquals(driver.getContextHandles().size(), 2); + } + + @Test public void testSwitchContext() { + driver.getContextHandles(); + driver.context("WEBVIEW_io.appium.android.apis"); + assertEquals(driver.getContext(), "WEBVIEW_io.appium.android.apis"); + driver.context("NATIVE_APP"); + } + + @Test(expected = NoSuchContextException.class) public void testContextError() { + driver.context("Planet of the Ape-ium"); } - } - - @Test - public void testGetContext() { - assertEquals("NATIVE_APP", driver.getContext()); - } - - @Test - public void testGetContextHandles() { - assertEquals(driver.getContextHandles().size(), 2); - } - - @Test - public void testSwitchContext() { - driver.getContextHandles(); - driver.context("WEBVIEW_io.appium.android.apis"); - assertEquals(driver.getContext(), "WEBVIEW_io.appium.android.apis"); - driver.context("NATIVE_APP"); - } - - @Test(expected = NoSuchContextException.class) - public void testContextError() { - driver.context("Planet of the Ape-ium"); - } } diff --git a/src/test/java/io/appium/java_client/android/AndroidDriverTest.java b/src/test/java/io/appium/java_client/android/AndroidDriverTest.java index d2616afca..c199a1fdc 100644 --- a/src/test/java/io/appium/java_client/android/AndroidDriverTest.java +++ b/src/test/java/io/appium/java_client/android/AndroidDriverTest.java @@ -21,11 +21,7 @@ import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; import org.apache.commons.codec.binary.Base64; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.openqa.selenium.ScreenOrientation; import org.openqa.selenium.WebElement; import org.openqa.selenium.html5.Location; @@ -34,243 +30,221 @@ import java.io.File; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; /** * Test Mobile Driver features */ public class AndroidDriverTest { - private AndroidDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "ApiDemos-debug.apk"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120); - driver = new AndroidDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - private String currentActivity() { - String currentActivity = null; - while (currentActivity == null) { - currentActivity = driver.currentActivity(); - Thread.yield(); + private static AppiumDriverLocalService service; + private AndroidDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "ApiDemos-debug.apk"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120); + driver = new AndroidDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + private String currentActivity() { + String currentActivity = null; + while (currentActivity == null) { + currentActivity = driver.currentActivity(); + Thread.yield(); + } + return currentActivity; + } + + @Test public void getDeviceTimeTest() { + String time = driver.getDeviceTime(); + assertTrue(time.length() == 28); + } + + @Test public void getStringsTest() { + Map strings = driver.getAppStringMap(); + assertTrue(strings.size() > 100); + } + + @Test public void getStringsWithLanguageTest() { + Map strings = driver.getAppStringMap("en"); + assertTrue(strings.size() > 100); + } + + @Test public void pressKeyCodeTest() { + driver.pressKeyCode(AndroidKeyCode.HOME); + } + + @Test public void pressKeyCodeWithMetastateTest() { + driver.pressKeyCode(AndroidKeyCode.SPACE, AndroidKeyMetastate.META_SHIFT_ON); + } + + @Test public void longPressKeyCodeTest() { + driver.longPressKeyCode(AndroidKeyCode.HOME); + } + + @Test public void longPressKeyCodeWithMetastateTest() { + driver.longPressKeyCode(AndroidKeyCode.HOME, AndroidKeyMetastate.META_SHIFT_ON); + } + + @Test public void currentActivityTest() { + String activity = driver.currentActivity(); + assertEquals(".ApiDemos", activity); + } + + @Test public void isAppInstalledTest() { + assertTrue(driver.isAppInstalled("com.example.android.apis")); + } + + @Test public void isAppNotInstalledTest() { + assertFalse(driver.isAppInstalled("foo")); + } + + @Test public void closeAppTest() throws InterruptedException { + driver.closeApp(); + driver.launchApp(); + assertEquals(".ApiDemos", driver.currentActivity()); + } + + @Test public void pushFileTest() { + byte[] data = Base64.encodeBase64( + "The eventual code is no more than the deposit of your understanding. ~E. W. Dijkstra" + .getBytes()); + driver.pushFile("/data/local/tmp/remote.txt", data); + byte[] returnData = driver.pullFile("/data/local/tmp/remote.txt"); + String returnDataDecoded = new String(Base64.decodeBase64(returnData)); + assertEquals( + "The eventual code is no more than the deposit of your understanding. ~E. W. Dijkstra", + returnDataDecoded); + } + + @Test public void networkConnectionTest() { + NetworkConnectionSetting networkConnection = + new NetworkConnectionSetting(false, true, true); + + networkConnection.setData(false); + networkConnection.setWifi(false); + + + driver.setNetworkConnection(networkConnection); + networkConnection = driver.getNetworkConnection(); + + assertEquals(new NetworkConnectionSetting(false, false, false), networkConnection); + + } + + @Test public void ignoreUnimportantViews() { + driver.ignoreUnimportantViews(true); + boolean ignoreViews = + driver.getSettings().get(AppiumSetting.IGNORE_UNIMPORTANT_VIEWS.toString()) + .getAsBoolean(); + assertTrue(ignoreViews); + driver.ignoreUnimportantViews(false); + ignoreViews = driver.getSettings().get(AppiumSetting.IGNORE_UNIMPORTANT_VIEWS.toString()) + .getAsBoolean(); + assertFalse(ignoreViews); + } + + @Test public void startActivityInThisAppTest() { + driver.startActivity("io.appium.android.apis", ".os.MorseCode", null, null, false); + assertTrue(currentActivity().endsWith(".os.MorseCode")); + driver.findElementById("text").sendKeys("Text must be here!"); + driver.startActivity("io.appium.android.apis", + ".accessibility.AccessibilityNodeProviderActivity", null, null, false); + assertTrue(currentActivity().endsWith(".accessibility.AccessibilityNodeProviderActivity")); + driver.pressKeyCode(AndroidKeyCode.BACK); + assertTrue(currentActivity().endsWith(".os.MorseCode")); + assertEquals("Text must be here!", driver.findElementById("text").getText()); + } + + @Test public void stopAndStartActivityInThisAppTest() { + driver.startActivity("io.appium.android.apis", ".os.MorseCode", null, null); + assertTrue(currentActivity().endsWith(".os.MorseCode")); + driver.startActivity("io.appium.android.apis", + ".accessibility.AccessibilityNodeProviderActivity", null, null); + assertTrue(currentActivity().endsWith(".accessibility.AccessibilityNodeProviderActivity")); + driver.pressKeyCode(AndroidKeyCode.BACK); + assertFalse(currentActivity().endsWith(".os.MorseCode")); + } + + //TODO hideKeyboard() test + + @Test public void startActivityInAnotherAppTest() { + driver.startActivity("com.android.contacts", ".ContactsListActivity", null, null); + String activity = driver.currentActivity(); + assertTrue(activity.contains("Contact")); + } + + @Test public void scrollToTest() { + driver.scrollTo("View"); + WebElement views = driver.findElementByAccessibilityId("Views"); + assertNotNull(views); + } + + @Test public void scrollToExactTest() { + driver.scrollToExact("Views"); + WebElement views = driver.findElementByAccessibilityId("Views"); + assertNotNull(views); + } + + @Test public void toggleLocationServicesTest() { + driver.toggleLocationServices(); + } + + @Test public void geolocationTest() { + Location location = new Location(45, 45, 100); + driver.setLocation(location); + } + + @Test public void orientationTest() { + assertEquals(ScreenOrientation.PORTRAIT, driver.getOrientation()); + driver.rotate(ScreenOrientation.LANDSCAPE); + assertEquals(ScreenOrientation.LANDSCAPE, driver.getOrientation()); + driver.rotate(ScreenOrientation.PORTRAIT); + } + + @Test public void lockTest() { + driver.lockDevice(); + assertEquals(true, driver.isLocked()); + driver.unlockDevice(); + assertEquals(false, driver.isLocked()); + } + + @Test public void runAppInBackgroundTest() { + long time = System.currentTimeMillis(); + driver.runAppInBackground(4); + long timeAfter = System.currentTimeMillis(); + assert (timeAfter - time > 3000); + } + + @Test public void pullFileTest() { + byte[] data = + driver.pullFile("data/system/registered_services/android.content.SyncAdapter.xml"); + assert (data.length > 0); + } + + @Test public void resetTest() { + driver.resetApp(); } - return currentActivity; - } - - @Test - public void getDeviceTimeTest() { - String time = driver.getDeviceTime(); - assertTrue(time.length() == 28); - } - - @Test - public void getStringsTest() { - Map strings = driver.getAppStringMap(); - assertTrue(strings.size() > 100); - } - - @Test - public void getStringsWithLanguageTest() { - Map strings = driver.getAppStringMap("en"); - assertTrue(strings.size() > 100); - } - - @Test - public void pressKeyCodeTest() { - driver.pressKeyCode(AndroidKeyCode.HOME); - } - - @Test - public void pressKeyCodeWithMetastateTest() { - driver.pressKeyCode(AndroidKeyCode.SPACE, AndroidKeyMetastate.META_SHIFT_ON); - } - - @Test - public void longPressKeyCodeTest() { - driver.longPressKeyCode(AndroidKeyCode.HOME); - } - - @Test - public void longPressKeyCodeWithMetastateTest() { - driver.longPressKeyCode(AndroidKeyCode.HOME, AndroidKeyMetastate.META_SHIFT_ON); - } - - @Test - public void currentActivityTest() { - String activity = driver.currentActivity(); - assertEquals(".ApiDemos", activity); - } - - @Test - public void isAppInstalledTest() { - assertTrue(driver.isAppInstalled("com.example.android.apis")); - } - - @Test - public void isAppNotInstalledTest() { - assertFalse(driver.isAppInstalled("foo")); - } - - @Test - public void closeAppTest() throws InterruptedException { - driver.closeApp(); - driver.launchApp(); - assertEquals(".ApiDemos", driver.currentActivity()); - } - - @Test - public void pushFileTest() { - byte[] data = Base64.encodeBase64("The eventual code is no more than the deposit of your understanding. ~E. W. Dijkstra".getBytes()); - driver.pushFile("/data/local/tmp/remote.txt", data); - byte[] returnData = driver.pullFile("/data/local/tmp/remote.txt"); - String returnDataDecoded = new String(Base64.decodeBase64(returnData)); - assertEquals("The eventual code is no more than the deposit of your understanding. ~E. W. Dijkstra", returnDataDecoded); - } - - @Test - public void networkConnectionTest() { - NetworkConnectionSetting networkConnection = new NetworkConnectionSetting(false, true, true); - - networkConnection.setData(false); - networkConnection.setWifi(false); - - - driver.setNetworkConnection(networkConnection); - networkConnection = driver.getNetworkConnection(); - - assertEquals(new NetworkConnectionSetting(false, false, false), networkConnection); - - } - - @Test - public void ignoreUnimportantViews() { - driver.ignoreUnimportantViews(true); - boolean ignoreViews = driver.getSettings().get(AppiumSetting.IGNORE_UNIMPORTANT_VIEWS.toString()).getAsBoolean(); - assertTrue(ignoreViews); - driver.ignoreUnimportantViews(false); - ignoreViews = driver.getSettings().get(AppiumSetting.IGNORE_UNIMPORTANT_VIEWS.toString()).getAsBoolean(); - assertFalse(ignoreViews); - } - - @Test - public void startActivityInThisAppTest() { - driver.startActivity("io.appium.android.apis", ".os.MorseCode", null, null, false); - assertTrue(currentActivity().endsWith(".os.MorseCode")); - driver.findElementById("text").sendKeys("Text must be here!"); - driver.startActivity("io.appium.android.apis", ".accessibility.AccessibilityNodeProviderActivity", null, null, false); - assertTrue(currentActivity().endsWith(".accessibility.AccessibilityNodeProviderActivity")); - driver.pressKeyCode(AndroidKeyCode.BACK); - assertTrue(currentActivity().endsWith(".os.MorseCode")); - assertEquals("Text must be here!", driver.findElementById("text").getText()); - } - - @Test - public void stopAndStartActivityInThisAppTest() { - driver.startActivity("io.appium.android.apis", ".os.MorseCode", null, null); - assertTrue(currentActivity().endsWith(".os.MorseCode")); - driver.startActivity("io.appium.android.apis", ".accessibility.AccessibilityNodeProviderActivity", null, null); - assertTrue(currentActivity().endsWith(".accessibility.AccessibilityNodeProviderActivity")); - driver.pressKeyCode(AndroidKeyCode.BACK); - assertFalse(currentActivity().endsWith(".os.MorseCode")); - } - - @Test - public void startActivityInAnotherAppTest() { - driver.startActivity("com.android.contacts", ".ContactsListActivity", null, null); - String activity = driver.currentActivity(); - assertTrue(activity.contains("Contact")); - } - - //TODO hideKeyboard() test - - @Test - public void scrollToTest() { - driver.scrollTo("View"); - WebElement views = driver.findElementByAccessibilityId("Views"); - assertNotNull(views); - } - - @Test - public void scrollToExactTest() { - driver.scrollToExact("Views"); - WebElement views = driver.findElementByAccessibilityId("Views"); - assertNotNull(views); - } - - @Test - public void toggleLocationServicesTest() { - driver.toggleLocationServices(); - } - - @Test - public void geolocationTest() { - Location location = new Location(45, 45, 100); - driver.setLocation(location); - } - - @Test - public void orientationTest() { - assertEquals(ScreenOrientation.PORTRAIT, driver.getOrientation()); - driver.rotate(ScreenOrientation.LANDSCAPE); - assertEquals(ScreenOrientation.LANDSCAPE, driver.getOrientation()); - driver.rotate(ScreenOrientation.PORTRAIT); - } - - @Test - public void lockTest() { - driver.lockDevice(); - assertEquals(true, driver.isLocked()); - driver.unlockDevice(); - assertEquals(false, driver.isLocked()); - } - - @Test - public void runAppInBackgroundTest() { - long time = System.currentTimeMillis(); - driver.runAppInBackground(4); - long timeAfter = System.currentTimeMillis(); - assert(timeAfter - time > 3000); - } - - @Test - public void pullFileTest() { - byte[] data = driver.pullFile("data/system/registered_services/android.content.SyncAdapter.xml"); - assert(data.length > 0); - } - - @Test - public void resetTest() { - driver.resetApp(); - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } } diff --git a/src/test/java/io/appium/java_client/android/AndroidGestureTest.java b/src/test/java/io/appium/java_client/android/AndroidGestureTest.java index 1e2b6a93c..844322f26 100644 --- a/src/test/java/io/appium/java_client/android/AndroidGestureTest.java +++ b/src/test/java/io/appium/java_client/android/AndroidGestureTest.java @@ -16,18 +16,10 @@ package io.appium.java_client.android; -import io.appium.java_client.MobileBy; -import io.appium.java_client.MobileElement; -import io.appium.java_client.MultiTouchAction; -import io.appium.java_client.SwipeElementDirection; -import io.appium.java_client.TouchAction; +import io.appium.java_client.*; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; @@ -42,118 +34,113 @@ * Test Mobile Driver features */ public class AndroidGestureTest { - private AndroidDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "ApiDemos-debug.apk"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new AndroidDriver<>(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - @Test - public void MultiGestureSingleActionTest() throws InterruptedException { - //the underlying java library for Appium doesn't like multi-gestures with only a single action. - //but java-client should handle it, silently falling back to just performing a single action. - - MultiTouchAction multiTouch = new MultiTouchAction(driver); - TouchAction action0 = new TouchAction(driver).tap(100,300); - multiTouch.add(action0).perform(); - } - - @Test - public void dragNDropTest() { - - driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().description(\"Views\"))"); - driver.findElementByAccessibilityId("Views").click(); - - driver.findElement(MobileBy.AndroidUIAutomator("description(\"Drag and Drop\")")).click(); - WebElement actionBarTitle = driver.findElement(MobileBy.AndroidUIAutomator("text(\"Views/Drag and Drop\")")); - - assertEquals("Wrong title.", "Views/Drag and Drop", actionBarTitle.getText()); - WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); - WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); - - WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); - assertEquals("Drag text not empty", "", dragText.getText()); - - TouchAction dragNDrop = new TouchAction(driver).longPress(dragDot1).moveTo(dragDot3).release(); - dragNDrop.perform(); - - assertNotEquals("Drag text empty", "", dragText.getText()); - } - - @Test - public void TapSingleFingerTest() throws InterruptedException { - Thread.sleep(2500); - driver.tap(1,200,300,1000); - } - - @Test - public void elementGestureTest(){ - driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); - MobileElement e = driver.findElement(MobileBy.AccessibilityId("App")); - e.tap(1, 1500); - System.out.println("tap"); - MobileElement e2 = driver.findElementByClassName("android.widget.TextView"); - e2.zoom(); - System.out.println("zoom"); - e2.swipe(SwipeElementDirection.RIGHT,1000); - System.out.println("RIGHT"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.RIGHT, 1, 2, 1000); - System.out.println("RIGHT Left border + 10 Right border - 20"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.LEFT, 1000); - System.out.println("LEFT"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.LEFT, 1, 2, 1000); - System.out.println("LEFT Right border - 10 Left border + 20"); - - driver.pressKeyCode(AndroidKeyCode.BACK); - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.DOWN,1000); - System.out.println("DOWN"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.DOWN, 1, 2, 1000); - System.out.println("DOWN Top - 10 Bottom + 20"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.UP,1000); - System.out.println("UP"); - - e2 = driver.findElementByClassName("android.widget.TextView"); - e2.swipe(SwipeElementDirection.UP, 1, 2, 1000); - System.out.println("UP Bottom + 10 Top - 20"); - - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } + private static AppiumDriverLocalService service; + private AndroidDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "ApiDemos-debug.apk"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new AndroidDriver<>(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + @Test public void MultiGestureSingleActionTest() throws InterruptedException { + //the underlying java library for Appium doesn't like multi-gestures with only a single action. + //but java-client should handle it, silently falling back to just performing a single action. + + MultiTouchAction multiTouch = new MultiTouchAction(driver); + TouchAction action0 = new TouchAction(driver).tap(100, 300); + multiTouch.add(action0).perform(); + } + + @Test public void dragNDropTest() { + + driver.findElementByAndroidUIAutomator( + "new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().description(\"Views\"))"); + driver.findElementByAccessibilityId("Views").click(); + + driver.findElement(MobileBy.AndroidUIAutomator("description(\"Drag and Drop\")")).click(); + WebElement actionBarTitle = + driver.findElement(MobileBy.AndroidUIAutomator("text(\"Views/Drag and Drop\")")); + + assertEquals("Wrong title.", "Views/Drag and Drop", actionBarTitle.getText()); + WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); + WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); + + WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); + assertEquals("Drag text not empty", "", dragText.getText()); + + TouchAction dragNDrop = + new TouchAction(driver).longPress(dragDot1).moveTo(dragDot3).release(); + dragNDrop.perform(); + + assertNotEquals("Drag text empty", "", dragText.getText()); + } + + @Test public void TapSingleFingerTest() throws InterruptedException { + Thread.sleep(2500); + driver.tap(1, 200, 300, 1000); + } + + @Test public void elementGestureTest() { + driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); + MobileElement e = driver.findElement(MobileBy.AccessibilityId("App")); + e.tap(1, 1500); + System.out.println("tap"); + MobileElement e2 = driver.findElementByClassName("android.widget.TextView"); + e2.zoom(); + System.out.println("zoom"); + e2.swipe(SwipeElementDirection.RIGHT, 1000); + System.out.println("RIGHT"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.RIGHT, 1, 2, 1000); + System.out.println("RIGHT Left border + 10 Right border - 20"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.LEFT, 1000); + System.out.println("LEFT"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.LEFT, 1, 2, 1000); + System.out.println("LEFT Right border - 10 Left border + 20"); + + driver.pressKeyCode(AndroidKeyCode.BACK); + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.DOWN, 1000); + System.out.println("DOWN"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.DOWN, 1, 2, 1000); + System.out.println("DOWN Top - 10 Bottom + 20"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.UP, 1000); + System.out.println("UP"); + + e2 = driver.findElementByClassName("android.widget.TextView"); + e2.swipe(SwipeElementDirection.UP, 1, 2, 1000); + System.out.println("UP Bottom + 10 Top - 20"); + + } } diff --git a/src/test/java/io/appium/java_client/android/AndroidUIAutomatorTest.java b/src/test/java/io/appium/java_client/android/AndroidUIAutomatorTest.java index fba93bcbb..118f09abc 100644 --- a/src/test/java/io/appium/java_client/android/AndroidUIAutomatorTest.java +++ b/src/test/java/io/appium/java_client/android/AndroidUIAutomatorTest.java @@ -21,11 +21,7 @@ import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.remote.MobilePlatform; import io.appium.java_client.service.local.AppiumDriverLocalService; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; @@ -40,97 +36,90 @@ */ public class AndroidUIAutomatorTest { - private AndroidDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "ApiDemos-debug.apk"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new AndroidDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - @Test - public void findElementTest() { - WebElement element = driver.findElementByAndroidUIAutomator("new UiSelector().index(0)"); - assertEquals("android.widget.FrameLayout", element.getTagName()); - } - - @Test - public void findElementsTest() { - List elements = driver.findElementsByAndroidUIAutomator("new UiSelector().clickable(true)"); - assertTrue(elements.size() > 10); - } - - @Test - public void findElementByTest() { - AndroidElement element = driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().index(0)")); - assertEquals("android.widget.FrameLayout", element.getTagName()); - } - - @Test - public void findElementsByTest() { - List elements = driver.findElements(MobileBy.AndroidUIAutomator("new UiSelector().clickable(true)")); - assertTrue(elements.size() > 10); - } - - @Test - public void findChainedElementsTest() { - AndroidElement el1 = driver.findElementByAndroidUIAutomator("resourceId(\"android:id/content\")"); - MobileElement el2 = el1.findElement(MobileBy.AndroidUIAutomator("text(\"Accessibility\")")); - el2.click(); - AndroidElement el3 = driver.findElementByAndroidUIAutomator("text(\"Custom View\")"); - assertTrue(el3.isDisplayed()); - } - - @Test - public void replaceValue() { - String originalValue = "original value"; - String replacedValue = "replaced value"; - - driver.scrollToExact("Views").click(); - driver.findElementByAndroidUIAutomator("text(\"Controls\")").click(); - driver.findElementByAndroidUIAutomator("text(\"1. Light Theme\")").click(); - - AndroidElement editElement = driver.findElementByAndroidUIAutomator("resourceId(\"io.appium.android.apis:id/edit\")"); - - editElement.sendKeys(originalValue); - - assertEquals(originalValue, editElement.getText()); - - editElement.replaceValue(replacedValue); - - assertEquals(replacedValue, editElement.getText()); - } - - @Test(expected = IllegalArgumentException.class) - public void ErrorTest() { - driver.findElementByAndroidUIAutomator(null); - } - - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } -} \ No newline at end of file + private static AppiumDriverLocalService service; + private AndroidDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "ApiDemos-debug.apk"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new AndroidDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + @Test public void findElementTest() { + WebElement element = driver.findElementByAndroidUIAutomator("new UiSelector().index(0)"); + assertEquals("android.widget.FrameLayout", element.getTagName()); + } + + @Test public void findElementsTest() { + List elements = + driver.findElementsByAndroidUIAutomator("new UiSelector().clickable(true)"); + assertTrue(elements.size() > 10); + } + + @Test public void findElementByTest() { + AndroidElement element = + driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().index(0)")); + assertEquals("android.widget.FrameLayout", element.getTagName()); + } + + @Test public void findElementsByTest() { + List elements = + driver.findElements(MobileBy.AndroidUIAutomator("new UiSelector().clickable(true)")); + assertTrue(elements.size() > 10); + } + + @Test public void findChainedElementsTest() { + AndroidElement el1 = + driver.findElementByAndroidUIAutomator("resourceId(\"android:id/content\")"); + MobileElement el2 = el1.findElement(MobileBy.AndroidUIAutomator("text(\"Accessibility\")")); + el2.click(); + AndroidElement el3 = driver.findElementByAndroidUIAutomator("text(\"Custom View\")"); + assertTrue(el3.isDisplayed()); + } + + @Test public void replaceValue() { + String originalValue = "original value"; + String replacedValue = "replaced value"; + + driver.scrollToExact("Views").click(); + driver.findElementByAndroidUIAutomator("text(\"Controls\")").click(); + driver.findElementByAndroidUIAutomator("text(\"1. Light Theme\")").click(); + + AndroidElement editElement = driver + .findElementByAndroidUIAutomator("resourceId(\"io.appium.android.apis:id/edit\")"); + + editElement.sendKeys(originalValue); + + assertEquals(originalValue, editElement.getText()); + + editElement.replaceValue(replacedValue); + + assertEquals(replacedValue, editElement.getText()); + } + + @Test(expected = IllegalArgumentException.class) public void ErrorTest() { + driver.findElementByAndroidUIAutomator(null); + } +} diff --git a/src/test/java/io/appium/java_client/hello appium - saved page.htm b/src/test/java/io/appium/java_client/hello appium - saved page.htm index 5411519a0..633925c95 100644 --- a/src/test/java/io/appium/java_client/hello appium - saved page.htm +++ b/src/test/java/io/appium/java_client/hello appium - saved page.htm @@ -1,363 +1,793 @@  - + + + + - - - - -hello appium - Rezultate căutare Yahoo Romania - + + + + + + + + hello appium - Rezultate căutare Yahoo Romania + + + - + +
-

Yahoo Romania Căutare pe Web

-
- - -
-
-
- +

Yahoo Romania Căutare pe Web

- - -
-
-
-
-
- +
+ -
- -
- +
+
+ +
+ -
-
-
-
-
-
- +
+
+
-
    -
  1. -
-
-
-
-
-
- - +
+
+ +
+
+ + +
+
+
+
+
+ + +
Ajutor + +
+ +
+ +
+
+
+
+
+
+
+ +
+ +
+ +
+
+
+
+ + +
+ +
+ + +
+
+
+
+
+
+ + +
    +
  1. +
    +
    +

    github.com +

    + +
    github.com/.../src/io/appium/android/apis/app/HelloWorld.java +
    +
    +
    +

    We would like to show you a + description here but the site + won’t allow us.

    +
    +
  2. +
  3. +
    +
    +

    Newest ' appium' + Questions - Stack Overflow

    + +
    stackoverflow.com/questions/tagged/appiumÃŽn cache +
    +
    +
    +

    Q&A for professional and + enthusiast programmers ... + Tour Start here for a quick overview of the + site

    +
    +
  4. +
  5. +
    +
    +

    Hello + All, I have done + setup for appium on Mac... +

    + +
    www.linkedin.com/grp/post/5190708-5857830099017019392ÃŽn cache +
    +
    +
    +

    Apr 03, 2014 · + Gaurav Tiwari + QA Automation Engineer at S&P Capital + IQ. April 4, 2014. Hello All, + I have done setup for appium on Mac + for iOS, but when i launch the + appium ...

    +
    +
  6. +
  7. +
    + + +
    +

    Hello Appium, I have + a Selenium grid setup (machine + A) with multiple desktop nodes (Windows, + Linux, Mac,...) (machines B, C & + D). From a heavily firewalled machine in ... +

    +
    +
  8. +
  9. +
    + + +
    +

    Hi There, I am trying to + make a simple Drag & Drop + gesture using TouchAction in Appium + 1.2.2 .I am testing this on the + site Touch Punch Unfortunately I cannot get + it ...

    +
    +
  10. +
  11. +
    + +
    +

    这个问题我准备写个hello world. + (ADT + Appium + 在åŒä¸€å°æœºå™¨ä¸Š). 需è¦å‡†å¤‡çš„知识: 1. èƒ½çœ‹æ‡‚ä»£ç  2. 略懂 webdriver +

    +
    +
  12. +
  13. +
    + + +
    +

    Hello: "appium + --version" returns 1.3.7 as my + versiohn of Appium. my command line + on a MAC is : + /Applications/Appium.app/Contents/Resources/node_modules/appium/bin + ...

    +
    +
  14. +
  15. +
    +
    +

    android - + Activity used to start app + doesn't...

    + +
    stackoverflow.com/questions/20335305/activity-used-to-start-app...ÃŽn cache +
    +
    +
    +

    When I try using + Appium to test my Hello + World Android app, I get Activity used to + start app doesn't exist! Make sure + it exists I have an apk with a package in it + ...

    +
    +
  16. +
  17. +
    +
    +

    Applitools | + Can you please provide + an example of...

    + +
    support.applitools.com/customer/portal/questions/6091174-can-you...ÃŽn cache +
    +
    +
    +

    Can you please provide an + example of an Appium test + for Android with Applitools Eyes

    +
    +
  18. +
  19. +
    +
    +

    Appium + for Automating + Native iOS Apps | Assert...

    + +
    www.assertselenium.com/appium/appium-for-automating-native-ios-appsÃŽn cache +
    +
    +
    +

    Hello, I am a newbie + to mobile automation but + appium got me very curious. Is there + a way to come up with a screen + capture video on how to setup and run a + basic test ... +

    +
    +
  20. +
+
+
+
+
    +
  1. + +
  2. +
+
+
+ +
+
+
+
+ +
+ +
+
+
+ + + diff --git a/src/test/java/io/appium/java_client/ios/IOSAccessibilityIdTest.java b/src/test/java/io/appium/java_client/ios/IOSAccessibilityIdTest.java index 135352931..e74d76232 100644 --- a/src/test/java/io/appium/java_client/ios/IOSAccessibilityIdTest.java +++ b/src/test/java/io/appium/java_client/ios/IOSAccessibilityIdTest.java @@ -35,62 +35,55 @@ */ public class IOSAccessibilityIdTest { - private AppiumDriver driver; - private static AppiumDriverLocalService service; + private static AppiumDriverLocalService service; + private AppiumDriver driver; - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "UICatalog.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); - @After - public void tearDown() throws Exception { - driver.quit(); - } + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "UICatalog.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } - @Test - public void findElementTest() { - WebElement element = driver.findElementByAccessibilityId("UICatalog"); - assertNotNull(element); - } + @After public void tearDown() throws Exception { + driver.quit(); + } - @Test - public void findElementsTest() { - List elements = driver.findElementsByAccessibilityId("UICatalog"); - assertTrue(elements.size() > 0); - } + @Test public void findElementTest() { + WebElement element = driver.findElementByAccessibilityId("UICatalog"); + assertNotNull(element); + } - @Test - public void MobileElementByTest() { - WebElement element = driver.findElement(MobileBy.AccessibilityId("UICatalog")); - assertNotNull(element); - } + @Test public void findElementsTest() { + List elements = driver.findElementsByAccessibilityId("UICatalog"); + assertTrue(elements.size() > 0); + } - @Test - public void MobileElementsByTest() { - List elements = driver.findElements(MobileBy.AccessibilityId("UICatalog")); - assertTrue(elements.size() > 0); - } + @Test public void MobileElementByTest() { + WebElement element = driver.findElement(MobileBy.AccessibilityId("UICatalog")); + assertNotNull(element); + } - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } + @Test public void MobileElementsByTest() { + List elements = + driver.findElements(MobileBy.AccessibilityId("UICatalog")); + assertTrue(elements.size() > 0); + } } diff --git a/src/test/java/io/appium/java_client/ios/IOSContextTest.java b/src/test/java/io/appium/java_client/ios/IOSContextTest.java index 60738ccdd..ca424690c 100644 --- a/src/test/java/io/appium/java_client/ios/IOSContextTest.java +++ b/src/test/java/io/appium/java_client/ios/IOSContextTest.java @@ -20,7 +20,9 @@ import io.appium.java_client.NoSuchContextException; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; @@ -33,58 +35,52 @@ */ public class IOSContextTest { - private static AppiumDriver driver; - private static AppiumDriverLocalService service; + private static AppiumDriver driver; + private static AppiumDriverLocalService service; - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "WebViewApp.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } - - @AfterClass - public static void tearDown() throws Exception { - if (driver != null) { - driver.quit(); + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "WebViewApp.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); } - if (service.isRunning()) { - service.stop(); + @AfterClass public static void tearDown() throws Exception { + if (driver != null) { + driver.quit(); + } + + if (service.isRunning()) { + service.stop(); + } } - } - @Test - public void testGetContext() { - assertEquals("NATIVE_APP", driver.getContext()); - } + @Test public void testGetContext() { + assertEquals("NATIVE_APP", driver.getContext()); + } - @Test - public void testGetContextHandles() { - assertEquals(driver.getContextHandles().size(), 2); - } + @Test public void testGetContextHandles() { + assertEquals(driver.getContextHandles().size(), 2); + } - @Test - public void testSwitchContext() { - driver.getContextHandles(); - driver.context("WEBVIEW_1"); - assertEquals(driver.getContext(), "WEBVIEW_1"); - driver.context("NATIVE_APP"); - } + @Test public void testSwitchContext() { + driver.getContextHandles(); + driver.context("WEBVIEW_1"); + assertEquals(driver.getContext(), "WEBVIEW_1"); + driver.context("NATIVE_APP"); + } - @Test(expected = NoSuchContextException.class) - public void testContextError() { - driver.context("Planet of the Ape-ium"); - } + @Test(expected = NoSuchContextException.class) public void testContextError() { + driver.context("Planet of the Ape-ium"); + } } diff --git a/src/test/java/io/appium/java_client/ios/IOSDriverTest.java b/src/test/java/io/appium/java_client/ios/IOSDriverTest.java index 55f1b5f80..276a687ca 100644 --- a/src/test/java/io/appium/java_client/ios/IOSDriverTest.java +++ b/src/test/java/io/appium/java_client/ios/IOSDriverTest.java @@ -19,12 +19,9 @@ import io.appium.java_client.MobileElement; import io.appium.java_client.remote.HideKeyboardStrategy; import io.appium.java_client.remote.MobileCapabilityType; - import io.appium.java_client.service.local.AppiumDriverLocalService; import org.junit.*; - import org.openqa.selenium.Point; - import org.openqa.selenium.ScreenOrientation; import org.openqa.selenium.html5.Location; import org.openqa.selenium.remote.DesiredCapabilities; @@ -32,9 +29,7 @@ import java.io.File; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; /** @@ -42,137 +37,121 @@ */ public class IOSDriverTest { - private IOSDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "UICatalog.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - /** - * @Test - * TODO There is no ability to check this function usibg simulators. When CI will have been set up then this test will be returned - */ - public void getDeviceTimeTest() { - String time = driver.getDeviceTime(); - assertTrue(time.length() == 28); - } - - @Test - public void getStringsTest() { - Map strings = driver.getAppStringMap(); - assertTrue(strings.size() > 10); - } - - @Test - public void getStringsWithLanguageTest() { - Map strings = driver.getAppStringMap("en"); - assertTrue(strings.size() > 10); - } - - @Test - public void getStringsWithLanguageAndStringFileTest() { - Map strings = driver.getAppStringMap("en", "Localizable.strings"); - assertTrue(strings.size() > 10); - } - - @Test - public void getStringsWithUnknownStringFileTest() { - Map strings = driver.getAppStringMap("en", "Unknown.strings"); - assertTrue(strings.size() > 10); - } - - @Test - public void resetTest() { - driver.resetApp(); - } - - @Test - public void namedTextFieldTest() { - MobileElement element = driver.findElementByAccessibilityId("Text Fields, AAPLTextFieldViewController"); - element.click(); - element = driver.getNamedTextField("DEFAULT"); - ((IOSElement) element).setValue("Grace Hopper"); - assertEquals("Grace Hopper", element.getText()); - } - - @Test - public void hideKeyboardWithParametersTest() { - MobileElement element = driver.findElementByAccessibilityId("Text Fields, AAPLTextFieldViewController"); - element.click(); - element = driver.findElementByAccessibilityId("DEFAULT"); - element.click(); - driver.hideKeyboard(HideKeyboardStrategy.PRESS_KEY, "Done"); - } - - @Test - public void scrollToTest() { - MobileElement searchBar = driver.findElementByName("Search Bars"); - Point before = searchBar.getLocation(); - driver.scrollTo("Search Ba"); - Point after = searchBar.getLocation(); - assertNotEquals(before, after); - } - - @Test - public void scrollToExactTest() { - MobileElement searchBar = driver.findElementByName("Search Bars"); - Point before = searchBar.getLocation(); - driver.scrollToExact("Search Bars"); - Point after = searchBar.getLocation(); - assertNotEquals(before, after); - } - - @Test - public void geolocationTest() { - Location location = new Location(45, 45, 100); - driver.setLocation(location); - } - - @Test - public void orientationTest() { - assertEquals(ScreenOrientation.PORTRAIT, driver.getOrientation()); - driver.rotate(ScreenOrientation.LANDSCAPE); - assertEquals(ScreenOrientation.LANDSCAPE, driver.getOrientation()); - driver.rotate(ScreenOrientation.PORTRAIT); - } - - @Test - public void lockTest() { - driver.lockDevice(20); - } - - @Test - public void pullFileTest() { - byte[] data = driver.pullFile("Library/AddressBook/AddressBook.sqlitedb"); - assert(data.length > 0); - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } + private static AppiumDriverLocalService service; + private IOSDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "UICatalog.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + /** + * @Test TODO There is no ability to check this function usibg simulators. When CI will have been set up then this test will be returned + */ + public void getDeviceTimeTest() { + String time = driver.getDeviceTime(); + assertTrue(time.length() == 28); + } + + @Test public void getStringsTest() { + Map strings = driver.getAppStringMap(); + assertTrue(strings.size() > 10); + } + + @Test public void getStringsWithLanguageTest() { + Map strings = driver.getAppStringMap("en"); + assertTrue(strings.size() > 10); + } + + @Test public void getStringsWithLanguageAndStringFileTest() { + Map strings = driver.getAppStringMap("en", "Localizable.strings"); + assertTrue(strings.size() > 10); + } + + @Test public void getStringsWithUnknownStringFileTest() { + Map strings = driver.getAppStringMap("en", "Unknown.strings"); + assertTrue(strings.size() > 10); + } + + @Test public void resetTest() { + driver.resetApp(); + } + + @Test public void namedTextFieldTest() { + MobileElement element = + driver.findElementByAccessibilityId("Text Fields, AAPLTextFieldViewController"); + element.click(); + element = driver.getNamedTextField("DEFAULT"); + ((IOSElement) element).setValue("Grace Hopper"); + assertEquals("Grace Hopper", element.getText()); + } + + @Test public void hideKeyboardWithParametersTest() { + MobileElement element = + driver.findElementByAccessibilityId("Text Fields, AAPLTextFieldViewController"); + element.click(); + element = driver.findElementByAccessibilityId("DEFAULT"); + element.click(); + driver.hideKeyboard(HideKeyboardStrategy.PRESS_KEY, "Done"); + } + + @Test public void scrollToTest() { + MobileElement searchBar = driver.findElementByName("Search Bars"); + Point before = searchBar.getLocation(); + driver.scrollTo("Search Ba"); + Point after = searchBar.getLocation(); + assertNotEquals(before, after); + } + + @Test public void scrollToExactTest() { + MobileElement searchBar = driver.findElementByName("Search Bars"); + Point before = searchBar.getLocation(); + driver.scrollToExact("Search Bars"); + Point after = searchBar.getLocation(); + assertNotEquals(before, after); + } + + @Test public void geolocationTest() { + Location location = new Location(45, 45, 100); + driver.setLocation(location); + } + + @Test public void orientationTest() { + assertEquals(ScreenOrientation.PORTRAIT, driver.getOrientation()); + driver.rotate(ScreenOrientation.LANDSCAPE); + assertEquals(ScreenOrientation.LANDSCAPE, driver.getOrientation()); + driver.rotate(ScreenOrientation.PORTRAIT); + } + + @Test public void lockTest() { + driver.lockDevice(20); + } + + @Test public void pullFileTest() { + byte[] data = driver.pullFile("Library/AddressBook/AddressBook.sqlitedb"); + assert (data.length > 0); + } } diff --git a/src/test/java/io/appium/java_client/ios/IosUIAutomationTest.java b/src/test/java/io/appium/java_client/ios/IosUIAutomationTest.java index 95fdb820e..a1234ff59 100644 --- a/src/test/java/io/appium/java_client/ios/IosUIAutomationTest.java +++ b/src/test/java/io/appium/java_client/ios/IosUIAutomationTest.java @@ -18,7 +18,6 @@ import io.appium.java_client.MobileBy; import io.appium.java_client.remote.MobileCapabilityType; - import io.appium.java_client.service.local.AppiumDriverLocalService; import org.junit.*; import org.openqa.selenium.WebElement; @@ -34,67 +33,58 @@ */ public class IosUIAutomationTest { - private IOSDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "UICatalog.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - @Test - public void findElementTest() { - WebElement element = driver.findElementByIosUIAutomation(".elements()[0]"); - assertEquals(element.getAttribute("name"), "UICatalog"); - } - - @Test - public void findElementsTest() { - List elements = driver.findElementsByIosUIAutomation(".elements()"); - assertEquals(3, elements.size()); - } - - @Test - public void MobileElementByTest() { - WebElement element = driver.findElement(MobileBy.IosUIAutomation(".elements()[0]")); - assertEquals(element.getAttribute("name"), "UICatalog"); - } - - @Test - public void MobileElementsByTest() { - List elements = driver.findElements(MobileBy.IosUIAutomation(".elements()")); - assertEquals(3, elements.size()); - } - - @Test(expected = IllegalArgumentException.class) - public void ErrorTest() { - driver.findElementByIosUIAutomation(null); - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } + private static AppiumDriverLocalService service; + private IOSDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "UICatalog.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + @Test public void findElementTest() { + WebElement element = driver.findElementByIosUIAutomation(".elements()[0]"); + assertEquals(element.getAttribute("name"), "UICatalog"); + } + + @Test public void findElementsTest() { + List elements = driver.findElementsByIosUIAutomation(".elements()"); + assertEquals(3, elements.size()); + } + + @Test public void MobileElementByTest() { + WebElement element = driver.findElement(MobileBy.IosUIAutomation(".elements()[0]")); + assertEquals(element.getAttribute("name"), "UICatalog"); + } + + @Test public void MobileElementsByTest() { + List elements = driver.findElements(MobileBy.IosUIAutomation(".elements()")); + assertEquals(3, elements.size()); + } + + @Test(expected = IllegalArgumentException.class) public void ErrorTest() { + driver.findElementByIosUIAutomation(null); + } } diff --git a/src/test/java/io/appium/java_client/ios/iOSGestureTest.java b/src/test/java/io/appium/java_client/ios/iOSGestureTest.java index 0abc2cd1b..349a74996 100644 --- a/src/test/java/io/appium/java_client/ios/iOSGestureTest.java +++ b/src/test/java/io/appium/java_client/ios/iOSGestureTest.java @@ -33,124 +33,116 @@ */ public class iOSGestureTest { - private AppiumDriver driver; - private static AppiumDriverLocalService service; - - @BeforeClass - public static void beforeClass() throws Exception{ - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - } - - @Before - public void setup() throws Exception { - if (service == null || !service.isRunning()) - throw new RuntimeException("An appium server node is not started!"); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "TestApp.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - @Test - public void TouchActionTest() throws InterruptedException { - WebElement button = driver.findElementsByClassName("UIAButton").get(3); - TouchAction action = new TouchAction(driver); - action.press(button).perform(); - Thread.sleep(2000); - } - - @Test - public void TouchActionChainTest() throws InterruptedException { - WebDriverWait wait = new WebDriverWait(driver, 2); - - WebElement button = driver.findElementsByClassName("UIAButton").get(5); - TouchAction action = new TouchAction(driver); - action.press(button).perform(); - - wait.until(ExpectedConditions.alertIsPresent()); - Alert alert = driver.switchTo().alert(); - alert.accept(); - - WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); - action = new TouchAction(driver); - action.press(mapview).moveTo(mapview, 0, 100).release().perform(); - Thread.sleep(2000); - } - - @Test - public void MultiGestureTest() throws InterruptedException { - WebDriverWait wait = new WebDriverWait(driver, 2); - - WebElement button = driver.findElementsByClassName("UIAButton").get(5); - TouchAction action = new TouchAction(driver); - action.press(button).perform(); - - wait.until(ExpectedConditions.alertIsPresent()); - Alert alert = driver.switchTo().alert(); - alert.accept(); - - WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); - - MultiTouchAction multiTouch = new MultiTouchAction(driver); - TouchAction action0 = new TouchAction(driver).press(mapview, 100, 0).moveTo(mapview, 0,-80).release(); - TouchAction action1 = new TouchAction(driver).press(mapview, 100, 50).moveTo(mapview, 0,80).release(); - multiTouch.add(action0).add(action1).perform(); - Thread.sleep(2000); - } - - @Test - public void ZoomTest() throws InterruptedException { - WebDriverWait wait = new WebDriverWait(driver, 2); - - WebElement button = driver.findElementsByClassName("UIAButton").get(5); - TouchAction action = new TouchAction(driver); - action.press(button).perform(); - - wait.until(ExpectedConditions.alertIsPresent()); - Alert alert = driver.switchTo().alert(); - alert.accept(); - - WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); - - driver.zoom(mapview); - Thread.sleep(2000); - } - - @Test - public void TapSingleFingerTest() { - driver.tap(1,100,200,1000); - } - - @Test - public void elementGestureTest(){ - MobileElement e = (MobileElement) driver.findElementByName("TextField1"); - e.tap(1, 1500); - e.zoom(); - e.pinch(); - e.swipe(SwipeElementDirection.UP,2000); - e.swipe(SwipeElementDirection.UP, 5, 5, 2000); - e.swipe(SwipeElementDirection.DOWN,2000); - e.swipe(SwipeElementDirection.DOWN, 5, 5, 2000); - e.swipe(SwipeElementDirection.LEFT,2000); - e.swipe(SwipeElementDirection.LEFT, 5, 5, 2000); - e.swipe(SwipeElementDirection.RIGHT,2000); - e.swipe(SwipeElementDirection.RIGHT, 5, 5, 2000); - } - - @AfterClass - public static void afterClass(){ - if (service != null) - service.stop(); - } + private static AppiumDriverLocalService service; + private AppiumDriver driver; + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + } + + @AfterClass public static void afterClass() { + if (service != null) + service.stop(); + } + + @Before public void setup() throws Exception { + if (service == null || !service.isRunning()) + throw new RuntimeException("An appium server node is not started!"); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "TestApp.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + @Test public void TouchActionTest() throws InterruptedException { + WebElement button = driver.findElementsByClassName("UIAButton").get(3); + TouchAction action = new TouchAction(driver); + action.press(button).perform(); + Thread.sleep(2000); + } + + @Test public void TouchActionChainTest() throws InterruptedException { + WebDriverWait wait = new WebDriverWait(driver, 2); + + WebElement button = driver.findElementsByClassName("UIAButton").get(5); + TouchAction action = new TouchAction(driver); + action.press(button).perform(); + + wait.until(ExpectedConditions.alertIsPresent()); + Alert alert = driver.switchTo().alert(); + alert.accept(); + + WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); + action = new TouchAction(driver); + action.press(mapview).moveTo(mapview, 0, 100).release().perform(); + Thread.sleep(2000); + } + + @Test public void MultiGestureTest() throws InterruptedException { + WebDriverWait wait = new WebDriverWait(driver, 2); + + WebElement button = driver.findElementsByClassName("UIAButton").get(5); + TouchAction action = new TouchAction(driver); + action.press(button).perform(); + + wait.until(ExpectedConditions.alertIsPresent()); + Alert alert = driver.switchTo().alert(); + alert.accept(); + + WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); + + MultiTouchAction multiTouch = new MultiTouchAction(driver); + TouchAction action0 = + new TouchAction(driver).press(mapview, 100, 0).moveTo(mapview, 0, -80).release(); + TouchAction action1 = + new TouchAction(driver).press(mapview, 100, 50).moveTo(mapview, 0, 80).release(); + multiTouch.add(action0).add(action1).perform(); + Thread.sleep(2000); + } + + @Test public void ZoomTest() throws InterruptedException { + WebDriverWait wait = new WebDriverWait(driver, 2); + + WebElement button = driver.findElementsByClassName("UIAButton").get(5); + TouchAction action = new TouchAction(driver); + action.press(button).perform(); + + wait.until(ExpectedConditions.alertIsPresent()); + Alert alert = driver.switchTo().alert(); + alert.accept(); + + WebElement mapview = driver.findElementByXPath("//UIAWindow[1]/UIAMapView[1]"); + + driver.zoom(mapview); + Thread.sleep(2000); + } + + @Test public void TapSingleFingerTest() { + driver.tap(1, 100, 200, 1000); + } + + @Test public void elementGestureTest() { + MobileElement e = (MobileElement) driver.findElementByName("TextField1"); + e.tap(1, 1500); + e.zoom(); + e.pinch(); + e.swipe(SwipeElementDirection.UP, 2000); + e.swipe(SwipeElementDirection.UP, 5, 5, 2000); + e.swipe(SwipeElementDirection.DOWN, 2000); + e.swipe(SwipeElementDirection.DOWN, 5, 5, 2000); + e.swipe(SwipeElementDirection.LEFT, 2000); + e.swipe(SwipeElementDirection.LEFT, 5, 5, 2000); + e.swipe(SwipeElementDirection.RIGHT, 2000); + e.swipe(SwipeElementDirection.RIGHT, 5, 5, 2000); + } } diff --git a/src/test/java/io/appium/java_client/localserver/ServerBuilderTest.java b/src/test/java/io/appium/java_client/localserver/ServerBuilderTest.java index 09601b110..80a19b8c0 100644 --- a/src/test/java/io/appium/java_client/localserver/ServerBuilderTest.java +++ b/src/test/java/io/appium/java_client/localserver/ServerBuilderTest.java @@ -20,6 +20,7 @@ import java.net.NetworkInterface; import java.util.Enumeration; import java.util.Properties; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -28,22 +29,21 @@ public class ServerBuilderTest { private static Properties properties; private static String testIP; - @BeforeClass - public static void beforeClass() throws Exception{ - File file = new File("src/test/java/io/appium/java_client/localserver/custom_node_path.properties"); + @BeforeClass public static void beforeClass() throws Exception { + File file = + new File("src/test/java/io/appium/java_client/localserver/custom_node_path.properties"); FileInputStream fileInput = new FileInputStream(file); properties = new Properties(); properties.load(fileInput); fileInput.close(); - for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) - { + for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en + .hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); - for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) - { + for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr + .hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); - if (!inetAddress.isLoopbackAddress()) - { + if (!inetAddress.isLoopbackAddress()) { InetAddressValidator validator = InetAddressValidator.getInstance(); testIP = inetAddress.getHostAddress().toString(); if (validator.isValid(testIP)) { @@ -58,7 +58,7 @@ public static void beforeClass() throws Exception{ } } - private static File findCustomNode(){ + private static File findCustomNode() { Platform current = Platform.getCurrent(); if (current.is(Platform.WINDOWS)) return new File(String.valueOf(properties.get("path.to.custom.node.win"))); @@ -69,20 +69,17 @@ private static File findCustomNode(){ return new File(String.valueOf(properties.get("path.to.custom.node.linux"))); } - @Test - public void checkAbilityToBuildDefaultService(){ + @Test public void checkAbilityToBuildDefaultService() { AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService(); try { service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { service.stop(); } } - @Test - public void checkAbilityToBuildServiceUsingNodeDefinedInProperties(){ + @Test public void checkAbilityToBuildServiceUsingNodeDefinedInProperties() { AppiumDriverLocalService service = null; try { String definedNode = findCustomNode().getAbsolutePath(); @@ -90,8 +87,7 @@ public void checkAbilityToBuildServiceUsingNodeDefinedInProperties(){ service = AppiumDriverLocalService.buildDefaultService(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } @@ -99,70 +95,63 @@ public void checkAbilityToBuildServiceUsingNodeDefinedInProperties(){ } } - @Test - public void checkAbilityToBuildServiceUsingNodeDefinedExplicitly(){ + @Test public void checkAbilityToBuildServiceUsingNodeDefinedExplicitly() { AppiumDriverLocalService service = null; try { File node = findCustomNode(); service = new AppiumServiceBuilder().withAppiumJS(node).build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToStartServiceOnAFreePort() { + @Test public void checkAbilityToStartServiceOnAFreePort() { AppiumDriverLocalService service = null; try { service = new AppiumServiceBuilder().usingAnyFreePort().build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToStartServiceUsingNonLocalhostIP() throws Exception { + @Test public void checkAbilityToStartServiceUsingNonLocalhostIP() throws Exception { AppiumDriverLocalService service = null; try { service = new AppiumServiceBuilder().withIPAddress(testIP).build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToStartServiceUsingFlags() throws Exception { + @Test public void checkAbilityToStartServiceUsingFlags() throws Exception { AppiumDriverLocalService service = null; try { - service = new AppiumServiceBuilder().withArgument(GeneralServerFlag.CALLBACK_ADDRESS, testIP). - withArgument(GeneralServerFlag.SESSION_OVERRIDE).withArgument(GeneralServerFlag.PRE_LAUNCH).build(); + service = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.CALLBACK_ADDRESS, testIP). + withArgument(GeneralServerFlag.SESSION_OVERRIDE) + .withArgument(GeneralServerFlag.PRE_LAUNCH).build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToStartServiceUsingCapabilities() throws Exception { + @Test public void checkAbilityToStartServiceUsingCapabilities() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); @@ -174,26 +163,26 @@ public void checkAbilityToStartServiceUsingCapabilities() throws Exception { capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); capabilities.setCapability(MobileCapabilityType.FULL_RESET, true); capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60); - capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); + capabilities + .setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - capabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); + capabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, + chrome.getAbsolutePath()); AppiumDriverLocalService service = null; try { service = new AppiumServiceBuilder().withCapabilities(capabilities).build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToStartServiceUsingCapabilitiesAndFlags() throws Exception { + @Test public void checkAbilityToStartServiceUsingCapabilitiesAndFlags() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); @@ -205,28 +194,30 @@ public void checkAbilityToStartServiceUsingCapabilitiesAndFlags() throws Excepti capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); capabilities.setCapability(MobileCapabilityType.FULL_RESET, true); capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60); - capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); + capabilities + .setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - capabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); + capabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, + chrome.getAbsolutePath()); AppiumDriverLocalService service = null; try { - service = new AppiumServiceBuilder().withArgument(GeneralServerFlag.CALLBACK_ADDRESS, testIP). - withArgument(GeneralServerFlag.SESSION_OVERRIDE).withArgument(GeneralServerFlag.PRE_LAUNCH). + service = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.CALLBACK_ADDRESS, testIP). + withArgument(GeneralServerFlag.SESSION_OVERRIDE) + .withArgument(GeneralServerFlag.PRE_LAUNCH). withCapabilities(capabilities).build(); service.start(); assertEquals(true, service.isRunning()); - } - finally { + } finally { if (service != null) { service.stop(); } } } - @Test - public void checkAbilityToChangeOutputStream() throws Exception{ + @Test public void checkAbilityToChangeOutputStream() throws Exception { File file = new File("target/test"); file.createNewFile(); OutputStream stream = new FileOutputStream(file); @@ -235,8 +226,7 @@ public void checkAbilityToChangeOutputStream() throws Exception{ try { service.start(); assertTrue(file.length() > 0); - } - finally { + } finally { service.stop(); if (stream != null) stream.close(); @@ -246,8 +236,7 @@ public void checkAbilityToChangeOutputStream() throws Exception{ } } - @Test - public void checkAbilityToChangeOutputStreamAfterTheServiceIsStarted() throws Exception{ + @Test public void checkAbilityToChangeOutputStreamAfterTheServiceIsStarted() throws Exception { File file = new File("target/test"); file.createNewFile(); OutputStream stream = new FileOutputStream(file); @@ -257,8 +246,7 @@ public void checkAbilityToChangeOutputStreamAfterTheServiceIsStarted() throws Ex service.addOutPutStream(stream); service.isRunning(); assertTrue(file.length() > 0); - } - finally { + } finally { service.stop(); if (stream != null) stream.close(); @@ -268,16 +256,14 @@ public void checkAbilityToChangeOutputStreamAfterTheServiceIsStarted() throws Ex } } - @Test - public void checkAbilityToShutDownService() { + @Test public void checkAbilityToShutDownService() { AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService(); service.start(); service.stop(); assertTrue(!service.isRunning()); } - @Test - public void checkAbilityToStartAndShutDownFewServices() throws Exception{ + @Test public void checkAbilityToStartAndShutDownFewServices() throws Exception { AppiumDriverLocalService service1 = new AppiumServiceBuilder().usingAnyFreePort().build(); AppiumDriverLocalService service2 = new AppiumServiceBuilder().usingAnyFreePort().build(); AppiumDriverLocalService service3 = new AppiumServiceBuilder().usingAnyFreePort().build(); @@ -299,8 +285,7 @@ public void checkAbilityToStartAndShutDownFewServices() throws Exception{ assertTrue(!service4.isRunning()); } - @Test - public void checkAbilityToStartServiceWithLogFile() throws Exception { + @Test public void checkAbilityToStartServiceWithLogFile() throws Exception { AppiumDriverLocalService service = null; File rootLogDir = new File("target/"); File log = new File(rootLogDir, "Log.txt"); @@ -310,8 +295,7 @@ public void checkAbilityToStartServiceWithLogFile() throws Exception { service.start(); assertEquals(true, log.exists()); assertEquals(true, log.length() > 0); - } - finally { + } finally { if (log.exists()) { log.delete(); } diff --git a/src/test/java/io/appium/java_client/localserver/StartingAppLocallyTest.java b/src/test/java/io/appium/java_client/localserver/StartingAppLocallyTest.java index 4a69df1c9..cc9362516 100644 --- a/src/test/java/io/appium/java_client/localserver/StartingAppLocallyTest.java +++ b/src/test/java/io/appium/java_client/localserver/StartingAppLocallyTest.java @@ -33,8 +33,7 @@ public class StartingAppLocallyTest { - @Test - public void startingAndroidAppWithCapabilitiesOnlyTest(){ + @Test public void startingAndroidAppWithCapabilitiesOnlyTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); @@ -42,45 +41,47 @@ public void startingAndroidAppWithCapabilitiesOnlyTest(){ capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); - AndroidDriver driver = new AndroidDriver<>(capabilities);; + AndroidDriver driver = new AndroidDriver<>(capabilities); + ; try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); + assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME) + .equals(AutomationName.APPIUM)); + assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME) + .equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); - } - finally { + assertEquals(true, + caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); + } finally { driver.quit(); } } - @Test - public void startingAndroidAppWithCapabilitiesAndServiceTest(){ + @Test public void startingAndroidAppWithCapabilitiesAndServiceTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). withArgument(GeneralServerFlag.STRICT_CAPS); AndroidDriver driver = new AndroidDriver<>(builder, capabilities); try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); + assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME) + .equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } - @Test - public void startingAndroidAppWithCapabilitiesOnServerSideTest(){ + @Test public void startingAndroidAppWithCapabilitiesOnServerSideTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); @@ -93,28 +94,31 @@ public void startingAndroidAppWithCapabilitiesOnServerSideTest(){ serverCapabilities.setCapability(MobileCapabilityType.FULL_RESET, true); serverCapabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60); serverCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - serverCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); + serverCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, + chrome.getAbsolutePath()); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withCapabilities(serverCapabilities); + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withCapabilities(serverCapabilities); DesiredCapabilities clientCapabilities = new DesiredCapabilities(); - clientCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); - clientCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); + clientCapabilities + .setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); + clientCapabilities + .setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); AndroidDriver driver = new AndroidDriver<>(builder, clientCapabilities); try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); + assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME) + .equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } - @Test - public void startingAndroidAppWithCapabilitiesAndFlagsOnServerSideTest(){ + @Test public void startingAndroidAppWithCapabilitiesAndFlagsOnServerSideTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); @@ -127,29 +131,32 @@ public void startingAndroidAppWithCapabilitiesAndFlagsOnServerSideTest(){ serverCapabilities.setCapability(MobileCapabilityType.FULL_RESET, true); serverCapabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60); serverCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - serverCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); + serverCapabilities.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE, + chrome.getAbsolutePath()); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). withArgument(GeneralServerFlag.STRICT_CAPS).withCapabilities(serverCapabilities); DesiredCapabilities clientCapabilities = new DesiredCapabilities(); - clientCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); - clientCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); + clientCapabilities + .setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis"); + clientCapabilities + .setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1"); AndroidDriver driver = new AndroidDriver<>(builder, clientCapabilities); try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); + assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME) + .equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } - @Test - public void startingIOSAppWithCapabilitiesOnlyTest(){ + @Test public void startingIOSAppWithCapabilitiesOnlyTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); @@ -159,24 +166,27 @@ public void startingIOSAppWithCapabilitiesOnlyTest(){ capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); - IOSDriver driver = new IOSDriver<>(capabilities);; + IOSDriver driver = new IOSDriver<>(capabilities); + ; try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); + assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME) + .equals(AutomationName.APPIUM)); + assertEquals(true, + caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_VERSION).equals("8.4")); - assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); - } - finally { + assertEquals(true, + caps.getCapability(MobileCapabilityType.PLATFORM_VERSION).equals("8.4")); + assertEquals(true, + caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); + } finally { driver.quit(); } } - @Test - public void startingIOSAppWithCapabilitiesAndServiseTest(){ + @Test public void startingIOSAppWithCapabilitiesAndServiseTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); @@ -186,72 +196,77 @@ public void startingIOSAppWithCapabilitiesAndServiseTest(){ capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). withArgument(GeneralServerFlag.STRICT_CAPS); IOSDriver driver = new IOSDriver<>(builder, capabilities); try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); + assertEquals(true, + caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } - @Test - public void startingIOSAppWithCapabilitiesOnServerSideTest(){ + @Test public void startingIOSAppWithCapabilitiesOnServerSideTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); DesiredCapabilities serverCapabilities = new DesiredCapabilities(); serverCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - serverCapabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); //some environment is too slow + serverCapabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, + 500000); //some environment is too slow serverCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); DesiredCapabilities clientCapabilities = new DesiredCapabilities(); clientCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withCapabilities(serverCapabilities); + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withCapabilities(serverCapabilities); - IOSDriver driver = new IOSDriver<>(builder, clientCapabilities);; + IOSDriver driver = new IOSDriver<>(builder, clientCapabilities); + ; try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); + assertEquals(true, + caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } - @Test - public void startingIOSAppWithCapabilitiesAndFlagsOnServerSideTest(){ + @Test public void startingIOSAppWithCapabilitiesAndFlagsOnServerSideTest() { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); DesiredCapabilities serverCapabilities = new DesiredCapabilities(); serverCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - serverCapabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); //some environment is too slow + serverCapabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, + 500000); //some environment is too slow serverCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); DesiredCapabilities clientCapabilities = new DesiredCapabilities(); clientCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - AppiumServiceBuilder builder = new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). + AppiumServiceBuilder builder = + new AppiumServiceBuilder().withArgument(GeneralServerFlag.SESSION_OVERRIDE). withArgument(GeneralServerFlag.STRICT_CAPS).withCapabilities(serverCapabilities); - IOSDriver driver = new IOSDriver<>(builder, clientCapabilities);; + IOSDriver driver = new IOSDriver<>(builder, clientCapabilities); + ; try { Capabilities caps = driver.getCapabilities(); - assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); + assertEquals(true, + caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.IOS)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); - } - finally { + } finally { driver.quit(); } } -} \ No newline at end of file +} diff --git a/src/test/java/io/appium/java_client/localserver/ThreadSafetyTest.java b/src/test/java/io/appium/java_client/localserver/ThreadSafetyTest.java index 60b3c3892..67d89a0cf 100644 --- a/src/test/java/io/appium/java_client/localserver/ThreadSafetyTest.java +++ b/src/test/java/io/appium/java_client/localserver/ThreadSafetyTest.java @@ -8,70 +8,29 @@ public class ThreadSafetyTest { - private static abstract class Action implements Cloneable { - abstract Object perform(); - - public Action clone() { - try { - return (Action) super.clone(); - } - catch (Throwable t) { - throw new RuntimeException(t); - } - } - } - - private static class TestThread implements Runnable { - private final Action action; - private Object result; - private Throwable t; - - TestThread(Action action) { - this.action = action; - } - - @Override - public void run() { - try { - result = action.perform(); - } - catch (Throwable t) { - this.t = t; - } - - } - } - final AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService(); final Action run = new Action() { - @Override - Object perform() { + @Override Object perform() { service.start(); return "OK"; } }; final Action run2 = run.clone(); - final Action isRunning = new Action() { - @Override - Object perform() { + @Override Object perform() { return service.isRunning(); } }; final Action isRunning2 = isRunning.clone(); - final Action stop = new Action() { - @Override - Object perform() { + @Override Object perform() { service.stop(); return "OK"; } }; - final Action stop2 = stop.clone(); - @Test - public void whenFewTreadsDoTheSameWork() throws Throwable { + @Test public void whenFewTreadsDoTheSameWork() throws Throwable { TestThread runTestThread = new TestThread(run); TestThread runTestThread2 = new TestThread(run2); @@ -147,8 +106,7 @@ public void whenFewTreadsDoTheSameWork() throws Throwable { assertTrue(stopTestThread.result.equals("OK")); assertTrue(stopTestThread2.result.equals("OK")); assertTrue(!service.isRunning()); - } - finally { + } finally { if (service.isRunning()) { service.stop(); } @@ -156,8 +114,7 @@ public void whenFewTreadsDoTheSameWork() throws Throwable { } - @Test - public void whenFewTreadsDoDifferentWork() throws Throwable { + @Test public void whenFewTreadsDoDifferentWork() throws Throwable { TestThread runTestThread = new TestThread(run); TestThread runTestThread2 = new TestThread(run2); @@ -199,9 +156,11 @@ public void whenFewTreadsDoDifferentWork() throws Throwable { throw stopTestThread.t; } - assertTrue(runTestThread.result.equals("OK")); //the service had been started firstly (see (1)) + assertTrue( + runTestThread.result.equals("OK")); //the service had been started firstly (see (1)) assertTrue(isRunningTestThread.result.equals(true)); //it was running (see (2)) - assertTrue(stopTestThread.result.equals("OK")); //and then the test tried to shut down it (see (3)) + assertTrue(stopTestThread.result + .equals("OK")); //and then the test tried to shut down it (see (3)) assertTrue(!service.isRunning()); isRunningThread2.start(); // (1) @@ -226,15 +185,49 @@ public void whenFewTreadsDoDifferentWork() throws Throwable { throw stopTestThread.t; } - assertTrue(isRunningTestThread2.result.equals(false)); //the service wasn't being running (see (1)) - assertTrue(stopTestThread2.result.equals("OK")); //the service had not been started firstly (see (2)), it is ok + assertTrue(isRunningTestThread2.result + .equals(false)); //the service wasn't being running (see (1)) + assertTrue(stopTestThread2.result + .equals("OK")); //the service had not been started firstly (see (2)), it is ok assertTrue(runTestThread2.result.equals("OK")); //and then it was started (see (3)) assertTrue(service.isRunning()); - } - finally { + } finally { if (service.isRunning()) { service.stop(); } } } + + + private static abstract class Action implements Cloneable { + abstract Object perform(); + + public Action clone() { + try { + return (Action) super.clone(); + } catch (Throwable t) { + throw new RuntimeException(t); + } + } + } + + + private static class TestThread implements Runnable { + private final Action action; + private Object result; + private Throwable t; + + TestThread(Action action) { + this.action = action; + } + + @Override public void run() { + try { + result = action.perform(); + } catch (Throwable t) { + this.t = t; + } + + } + } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/AndroidPageObjectTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/AndroidPageObjectTest.java index 9eea24f53..87e341d22 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/AndroidPageObjectTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/AndroidPageObjectTest.java @@ -51,17 +51,13 @@ public class AndroidPageObjectTest { private static AppiumDriverLocalService service; private boolean populated = false; - @FindBy(className = "android.widget.TextView") - private List textVieWs; + @FindBy(className = "android.widget.TextView") private List textVieWs; - @AndroidFindBy(className = "android.widget.TextView") - private List androidTextViews; + @AndroidFindBy(className = "android.widget.TextView") private List androidTextViews; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List iosTextViews; + @iOSFindBy(uiAutomator = ".elements()[0]") private List iosTextViews; - @iOSFindBy(uiAutomator = ".elements()[0]") - @AndroidFindBy(className = "android.widget.TextView") + @iOSFindBy(uiAutomator = ".elements()[0]") @AndroidFindBy(className = "android.widget.TextView") private List androidOriOsTextViews; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") @@ -70,45 +66,36 @@ public class AndroidPageObjectTest { @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private List mobileElementViews; - @FindBy(className = "android.widget.TextView") - private List mobiletextVieWs; + @FindBy(className = "android.widget.TextView") private List mobiletextVieWs; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private List remoteElementViews; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) - private List chainElementViews; + @AndroidFindBy(className = "android.widget.TextView")}) private List + chainElementViews; - @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), - @iOSFindBy(xpath = "//someElement")}) + @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), @iOSFindBy(xpath = "//someElement")}) private List iosChainTextViews; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")"), @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(id = "android:id/text1") - }) - @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), - @iOSFindBy(xpath = "//someElement")}) + @AndroidFindBy(id = "android:id/text1")}) + @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), @iOSFindBy(xpath = "//someElement")}) private List chainAndroidOrIOSUIAutomatorViews; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private List touchabletextVieWs; - @FindBy(id = "android:id/text1") - private WebElement textView; + @FindBy(id = "android:id/text1") private WebElement textView; - @AndroidFindBy(className = "android.widget.TextView") - private WebElement androidTextView; + @AndroidFindBy(className = "android.widget.TextView") private WebElement androidTextView; - @iOSFindBy(uiAutomator = ".elements()[0]") - private WebElement iosTextView; + @iOSFindBy(uiAutomator = ".elements()[0]") private WebElement iosTextView; - @AndroidFindBy(className = "android.widget.TextView") - @iOSFindBy(uiAutomator = ".elements()[0]") + @AndroidFindBy(className = "android.widget.TextView") @iOSFindBy(uiAutomator = ".elements()[0]") private WebElement androidOriOsTextView; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") @@ -117,85 +104,66 @@ public class AndroidPageObjectTest { @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private MobileElement mobileElementView; - @FindBy(className = "android.widget.TextView") - private MobileElement mobiletextVieW; + @FindBy(className = "android.widget.TextView") private MobileElement mobiletextVieW; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private RemoteWebElement remotetextVieW; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) - private WebElement chainElementView; + @AndroidFindBy(className = "android.widget.TextView")}) private WebElement chainElementView; - @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), - @iOSFindBy(xpath = "//someElement")}) + @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), @iOSFindBy(xpath = "//someElement")}) private WebElement iosChainTextView; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")"), @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(id = "android:id/text1") - }) - @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), - @iOSFindBy(xpath = "//someElement")}) + @AndroidFindBy(id = "android:id/text1")}) + @iOSFindBys({@iOSFindBy(uiAutomator = ".elements()[0]"), @iOSFindBy(xpath = "//someElement")}) private WebElement chainAndroidOrIOSUIAutomatorView; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")"), @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(id = "android:id/text1") - }) - private AndroidElement androidElementView; + @AndroidFindBy(id = "android:id/text1")}) private AndroidElement androidElementView; @AndroidFindBys({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/content\")"), @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(id = "android:id/text1") - }) - private List androidElementViews; + @AndroidFindBy(id = "android:id/text1")}) private List androidElementViews; @AndroidFindAll({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/Fakecontent\")"), @AndroidFindBy(id = "android:id/Faketext1"), - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), //by this locator element is found - @AndroidFindBy(id = "android:id/FakeId") - }) - private List findAllElementViews; + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), + //by this locator element is found + @AndroidFindBy(id = "android:id/FakeId")}) private List findAllElementViews; @AndroidFindAll({ @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/Fakecontent\")"), @AndroidFindBy(id = "android:id/Faketext1"), - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), //by this locator element is found - @AndroidFindBy(id = "android:id/FakeId") - }) - private WebElement findAllElementView; - - @AndroidFindBy(id = "android:id/text1") - @SelendroidFindBy(id = "Invalid Identifier") - private WebElement textAndroidId; + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), + //by this locator element is found + @AndroidFindBy(id = "android:id/FakeId")}) private WebElement findAllElementView; + + @AndroidFindBy(id = "android:id/text1") @SelendroidFindBy(id = "Invalid Identifier") + private WebElement textAndroidId; @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") private TouchableElement touchabletextVieW; - @iOSFindBy(uiAutomator = ".elements()[0]") - @FindBy(css = "e.e1.e2") - private List elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + @iOSFindBy(uiAutomator = ".elements()[0]") @FindBy(css = "e.e1.e2") private List + elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - @iOSFindBy(uiAutomator = ".elements()[0]") - @FindBy(css = "e.e1.e2") - private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + @iOSFindBy(uiAutomator = ".elements()[0]") @FindBy(css = "e.e1.e2") private WebElement + elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - @FindBy(id = "fakeId") - private WebElement fakeElement; + @FindBy(id = "fakeId") private WebElement fakeElement; - @FindBy(id = "fakeId") - private List fakeElements; + @FindBy(id = "fakeId") private List fakeElements; - @SuppressWarnings("rawtypes") - @BeforeClass - public static void beforeClass() throws Exception { + @SuppressWarnings("rawtypes") @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); @@ -207,8 +175,15 @@ public static void beforeClass() throws Exception { driver = new AndroidDriver<>(service.getUrl(), capabilities); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (driver != null) + driver.quit(); + + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { if (!populated) //This time out is set because test can be run on slow Android SDK emulator PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); @@ -216,209 +191,163 @@ public void setUp() throws Exception { populated = true; } - @AfterClass - public static void afterClass() throws Exception { - if (driver != null) - driver.quit(); - - if (service != null) - service.stop(); - } - - @Test - public void findByElementsTest() { + @Test public void findByElementsTest() { assertNotEquals(0, textVieWs.size()); } - @Test - public void findByElementTest() { + @Test public void findByElementTest() { assertNotEquals(null, textView.getAttribute("text")); } - @Test - public void androidFindByElementsTest(){ + @Test public void androidFindByElementsTest() { assertNotEquals(0, androidTextViews.size()); } - @Test - public void androidFindByElementTest(){ + @Test public void androidFindByElementTest() { assertNotEquals(null, androidTextView.getAttribute("text")); } - @Test - public void checkThatElementsWereNotFoundByIOSUIAutomator(){ + @Test public void checkThatElementsWereNotFoundByIOSUIAutomator() { assertEquals(0, iosTextViews.size()); } - @Test - public void checkThatElementWasNotFoundByIOSUIAutomator(){ + @Test public void checkThatElementWasNotFoundByIOSUIAutomator() { NoSuchElementException nsee = null; - try{ + try { iosTextView.getAttribute("text"); - } - catch (Exception e){ + } catch (Exception e) { nsee = (NoSuchElementException) e; } assertNotNull(nsee); } - @Test - public void androidOrIOSFindByElementsTest(){ + @Test public void androidOrIOSFindByElementsTest() { assertNotEquals(0, androidOriOsTextViews.size()); } - @Test - public void androidOrIOSFindByElementTest(){ + @Test public void androidOrIOSFindByElementTest() { assertNotEquals(null, androidOriOsTextView.getAttribute("text")); } - @Test - public void androidFindByUIAutomatorElementsTest(){ + @Test public void androidFindByUIAutomatorElementsTest() { assertNotEquals(0, androidUIAutomatorViews.size()); } - @Test - public void androidFindByUIAutomatorElementTest(){ + @Test public void androidFindByUIAutomatorElementTest() { assertNotEquals(null, androidUIAutomatorView.getAttribute("text")); } - @Test - public void areMobileElementsTest(){ + @Test public void areMobileElementsTest() { assertNotEquals(0, mobileElementViews.size()); } - @Test - public void isMobileElementTest(){ + @Test public void isMobileElementTest() { assertNotEquals(null, mobileElementView.getAttribute("text")); } - @Test - public void areMobileElements_FindByTest(){ + @Test public void areMobileElements_FindByTest() { assertNotEquals(0, mobiletextVieWs.size()); } - @Test - public void isMobileElement_FindByTest(){ + @Test public void isMobileElement_FindByTest() { assertNotEquals(null, mobiletextVieW.getAttribute("text")); } - @Test - public void areRemoteElementsTest(){ + @Test public void areRemoteElementsTest() { assertNotEquals(0, remoteElementViews.size()); } - @Test - public void isRemoteElementTest(){ + @Test public void isRemoteElementTest() { assertNotEquals(null, remotetextVieW.getAttribute("text")); } - @Test - public void androidChainSearchElementsTest(){ + @Test public void androidChainSearchElementsTest() { assertNotEquals(0, chainElementViews.size()); } - @Test - public void androidChainSearchElementTest(){ + @Test public void androidChainSearchElementTest() { assertNotEquals(null, chainElementView.getAttribute("text")); } - @Test - public void checkThatElementsWereNotFoundByIOSUIAutomator_Chain(){ + @Test public void checkThatElementsWereNotFoundByIOSUIAutomator_Chain() { assertEquals(0, iosChainTextViews.size()); } - @Test - public void checkThatElementWasNotFoundByIOSUIAutomator_Chain(){ + @Test public void checkThatElementWasNotFoundByIOSUIAutomator_Chain() { NoSuchElementException nsee = null; - try{ + try { iosChainTextView.getAttribute("text"); - } - catch (Exception e){ + } catch (Exception e) { nsee = (NoSuchElementException) e; } assertNotNull(nsee); } - @Test - public void androidOrIOSFindByElementsTest_ChainSearches(){ + @Test public void androidOrIOSFindByElementsTest_ChainSearches() { assertNotEquals(0, chainAndroidOrIOSUIAutomatorViews.size()); } - @Test - public void androidOrIOSFindByElementTest_ChainSearches(){ + @Test public void androidOrIOSFindByElementTest_ChainSearches() { assertNotEquals(null, chainAndroidOrIOSUIAutomatorView.getAttribute("text")); } - @Test - public void isAndroidElementTest(){ + @Test public void isAndroidElementTest() { assertNotEquals(null, androidElementView.getAttribute("text")); } - @Test - public void areAndroidElementsTest(){ + @Test public void areAndroidElementsTest() { assertNotEquals(0, androidElementViews.size()); } - @Test - public void findAllElementTest(){ + @Test public void findAllElementTest() { assertNotEquals(null, findAllElementView.getAttribute("text")); } - @Test - public void findAllElementsTest(){ + @Test public void findAllElementsTest() { assertNotEquals(0, findAllElementViews.size()); } - - @Test - public void findByAndroidAnnotationOnlyTest(){ + + @Test public void findByAndroidAnnotationOnlyTest() { assertNotEquals(null, textAndroidId.getAttribute("text")); } - @Test - public void isTouchableElement(){ + @Test public void isTouchableElement() { assertNotEquals(null, touchabletextVieW.getAttribute("text")); } - @Test - public void areTouchableElements(){ + @Test public void areTouchableElements() { assertNotEquals(0, touchabletextVieWs.size()); } - @Test - @SuppressWarnings("unused") - public void isTheFieldAndroidElement(){ + @Test @SuppressWarnings("unused") public void isTheFieldAndroidElement() { AndroidElement androidElement = (AndroidElement) mobiletextVieW; //declared as MobileElement androidElement = (AndroidElement) androidTextView; //declared as WedElement androidElement = (AndroidElement) remotetextVieW; //declared as RemoteWedElement androidElement = (AndroidElement) touchabletextVieW; //declared as TouchABLEElement } - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ + @Test public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy() { try { - assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); - } - catch (NoSuchElementException ignored){ + assertNotEquals(null, + elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); + } catch (NoSuchElementException ignored) { return; } throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); } - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ + @Test public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List() { assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); } - @Test - public void checkThatClassObjectMethodsDoNotInvokeTheSearching() { + @Test public void checkThatClassObjectMethodsDoNotInvokeTheSearching() { assertEquals(true, AndroidElement.class.isAssignableFrom(fakeElement.getClass())); assertEquals(false, AndroidElement.class.equals(fakeElement.getClass())); assertEquals(true, driver.equals(((WrapsDriver) fakeElement).getWrappedDriver())); } - @Test - public void checkThatClassObjectMethodsDoNotInvokeTheSearchingOfElementLest() { + @Test public void checkThatClassObjectMethodsDoNotInvokeTheSearchingOfElementLest() { assertEquals(true, List.class.isAssignableFrom(fakeElements.getClass())); assertEquals(false, ArrayList.class.equals(fakeElements.getClass())); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/DesktopBrowserCompatibilityTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/DesktopBrowserCompatibilityTest.java index 2f0e63303..bcf35f3a7 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/DesktopBrowserCompatibilityTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/DesktopBrowserCompatibilityTest.java @@ -41,49 +41,44 @@ public class DesktopBrowserCompatibilityTest { - public void setUp() { - if (current.is(Platform.WINDOWS)) { - System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); - } - else { - System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); - } - } - - private final Platform current = Platform.getCurrent(); - private final long IMPLICITLY_WAIT = 15; - - @AndroidFindBy(className = "someClass") - @iOSFindBys({ - @iOSFindBy(xpath = "//selector[1]"), - @iOSFindBy(xpath = "//someTag")}) - @FindBys({@FindBy(id="main"), @FindBy(tagName = "p")}) - private List foundLinks; - - private List main; //this list is located by id="main" + private final Platform current = Platform.getCurrent(); + private final long IMPLICITLY_WAIT = 15; + @AndroidFindBy(className = "someClass") + @iOSFindBys({@iOSFindBy(xpath = "//selector[1]"), @iOSFindBy(xpath = "//someTag")}) + @FindBys({@FindBy(id = "main"), @FindBy(tagName = "p")}) private List foundLinks; + private List main; //this list is located by id="main" + private WebDriver trap1; + private List> trap2; - private WebDriver trap1; - private List> trap2; - - private void test(){ - WebDriver driver = new ChromeDriver(); - try { - PageFactory.initElements(new AppiumFieldDecorator(driver, IMPLICITLY_WAIT, TimeUnit.SECONDS), this); - driver.get(new File("src/test/java/io/appium/java_client/hello appium - saved page.htm").toURI().toString()); - assertNotEquals(0, foundLinks.size()); - assertNotEquals(0, main.size()); - assertEquals(null, trap1); - assertEquals(null, trap2); - } finally { - driver.quit(); - } - } + public void setUp() { + if (current.is(Platform.WINDOWS)) { + System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); + } else { + System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); + } + } - @Test - public void chromeTest() { - setUp(); - test(); - } + private void test() { + WebDriver driver = new ChromeDriver(); + try { + PageFactory + .initElements(new AppiumFieldDecorator(driver, IMPLICITLY_WAIT, TimeUnit.SECONDS), + this); + driver.get(new File("src/test/java/io/appium/java_client/hello appium - saved page.htm") + .toURI().toString()); + assertNotEquals(0, foundLinks.size()); + assertNotEquals(0, main.size()); + assertEquals(null, trap1); + assertEquals(null, trap2); + } finally { + driver.quit(); + } + } + + @Test public void chromeTest() { + setUp(); + test(); + } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/IOSfMobileBrowserCompatibilityTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/IOSfMobileBrowserCompatibilityTest.java index 8798ea800..0232dfc3a 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/IOSfMobileBrowserCompatibilityTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/IOSfMobileBrowserCompatibilityTest.java @@ -39,51 +39,46 @@ public class IOSfMobileBrowserCompatibilityTest { - private WebDriver driver; + private WebDriver driver; private AppiumDriverLocalService service; - - @FindBy(className = "gsfi") - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/someId\")") - @iOSFindBy(className = "someClass") - private WebElement searchTextField; - - @AndroidFindBy(className = "someClass") - @FindBys({@FindBy(className = "r"), @FindBy(tagName = "a")}) - @iOSFindBy(className = "someClass") - private List foundLinks; - - @Before - public void setUp() throws Exception { + + @FindBy(className = "gsfi") + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/someId\")") + @iOSFindBy(className = "someClass") private WebElement searchTextField; + + @AndroidFindBy(className = "someClass") + @FindBys({@FindBy(className = "r"), @FindBy(tagName = "a")}) @iOSFindBy(className = "someClass") + private List foundLinks; + + @Before public void setUp() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.SAFARI); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - driver = new IOSDriver<>(service.getUrl(), capabilities); - PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); - } + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.SAFARI); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "8.4"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + driver = new IOSDriver<>(service.getUrl(), capabilities); + PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); + } - @After - public void tearDown() throws Exception { + @After public void tearDown() throws Exception { if (driver != null) driver.quit(); if (service != null) service.stop(); - } + } - @Test - public void test() { - driver.get("https://www.google.com"); + @Test public void test() { + driver.get("https://www.google.com"); - searchTextField.sendKeys("Hello"); - searchTextField.submit(); - Assert.assertNotEquals(0, foundLinks.size()); - searchTextField.clear(); - searchTextField.sendKeys("Hello, Appium!"); - searchTextField.submit(); - } + searchTextField.sendKeys("Hello"); + searchTextField.submit(); + Assert.assertNotEquals(0, foundLinks.size()); + searchTextField.clear(); + searchTextField.sendKeys("Hello, Appium!"); + searchTextField.submit(); + } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java index d20d6a0eb..b0aee9b91 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/MobileBrowserCompatibilityTest.java @@ -40,52 +40,47 @@ public class MobileBrowserCompatibilityTest { - private WebDriver driver; + private WebDriver driver; private AppiumDriverLocalService service; - - @AndroidFindBys({ - @AndroidFindBy(className = "someClass"), - @AndroidFindBy(xpath = "//someTag")}) - private RemoteWebElement btnG; //this element should be found by id = 'btnG' or name = 'btnG' - - @FindBy(className = "gsfi") - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/someId\")") - private WebElement searchTextField; - - @AndroidFindBy(className = "someClass") - @FindBys({@FindBy(className = "r"), @FindBy(tagName = "a")}) - private List foundLinks; - - @Before - public void setUp() throws Exception { + + @AndroidFindBys({@AndroidFindBy(className = "someClass"), @AndroidFindBy(xpath = "//someTag")}) + private RemoteWebElement btnG; //this element should be found by id = 'btnG' or name = 'btnG' + + @FindBy(className = "gsfi") + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/someId\")") + private WebElement searchTextField; + + @AndroidFindBy(className = "someClass") + @FindBys({@FindBy(className = "r"), @FindBy(tagName = "a")}) private List + foundLinks; + + @Before public void setUp() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.BROWSER); - driver = new AndroidDriver(service.getUrl(), capabilities); - //This time out is set because test can be run on slow Android SDK emulator - PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); - } + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.BROWSER); + driver = new AndroidDriver(service.getUrl(), capabilities); + //This time out is set because test can be run on slow Android SDK emulator + PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); + } - @After - public void tearDown() throws Exception { + @After public void tearDown() throws Exception { if (driver != null) driver.quit(); if (service != null) service.stop(); - } + } - @Test - public void test() { - driver.get("https://www.google.com"); + @Test public void test() { + driver.get("https://www.google.com"); - searchTextField.sendKeys("Hello"); - btnG.click(); - Assert.assertNotEquals(0, foundLinks.size()); - } + searchTextField.sendKeys("Hello"); + btnG.click(); + Assert.assertNotEquals(0, foundLinks.size()); + } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java index 846032801..1c8ec3a67 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/SelendroidModeTest.java @@ -18,15 +18,16 @@ import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; -import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.*; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.AutomationName; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; -import org.junit.*; -import org.openqa.selenium.WebDriver; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.FindBy; @@ -45,51 +46,34 @@ public class SelendroidModeTest { private static AppiumDriverLocalService service; private boolean populated = false; - @SelendroidFindBy(id = "text1") - private WebElement textId; + @SelendroidFindBy(id = "text1") private WebElement textId; - @AndroidFindBy(id = "Invalid Identifier") - @SelendroidFindBy(id = "text1") - private WebElement textSelendroidId; + @AndroidFindBy(id = "Invalid Identifier") @SelendroidFindBy(id = "text1") private WebElement + textSelendroidId; - @SelendroidFindBy(name = "Accessibility") - private WebElement textName; + @SelendroidFindBy(name = "Accessibility") private WebElement textName; - @AndroidFindBy(name = "Accessibility") - private WebElement textNameAndroid; + @AndroidFindBy(name = "Accessibility") private WebElement textNameAndroid; - @FindBy(name = "Accessibility") - private WebElement textNameDefault; + @FindBy(name = "Accessibility") private WebElement textNameDefault; - @SelendroidFindBy(xpath = "//TextView[@value='Accessibility']") - private WebElement textXpath; + @SelendroidFindBy(xpath = "//TextView[@value='Accessibility']") private WebElement textXpath; - @SelendroidFindBys({ - @SelendroidFindBy(id = "text1")}) - private WebElement textIds; + @SelendroidFindBys({@SelendroidFindBy(id = "text1")}) private WebElement textIds; - @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) - private WebElement textAll; + @SelendroidFindAll({@SelendroidFindBy(id = "text1")}) private WebElement textAll; - @SelendroidFindAll({ - @SelendroidFindBy(id = "text1")}) - private List textsAll; + @SelendroidFindAll({@SelendroidFindBy(id = "text1")}) private List textsAll; - @SelendroidFindBy(className = "android.widget.TextView") - private WebElement textClass; + @SelendroidFindBy(className = "android.widget.TextView") private WebElement textClass; - @SelendroidFindBy(tagName = "TextView") - private WebElement textTag; + @SelendroidFindBy(tagName = "TextView") private WebElement textTag; - @SelendroidFindBy(linkText = "Accessibility") - private WebElement textLink; + @SelendroidFindBy(linkText = "Accessibility") private WebElement textLink; - @SelendroidFindBy(partialLinkText = "ccessibilit") - private WebElement textPartialLink; + @SelendroidFindBy(partialLinkText = "ccessibilit") private WebElement textPartialLink; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { AppiumServiceBuilder builder = new AppiumServiceBuilder(); service = builder.build(); service.start(); @@ -105,17 +89,7 @@ public static void beforeClass() throws Exception { driver.context("NATIVE_APP"); } - @Before - public void setUp() throws Exception { - if (!populated) - //This time out is set because test can be run on slow Android SDK emulator - PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); - - populated = true; - } - - @AfterClass - public static void afterClass() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) driver.quit(); @@ -123,69 +97,64 @@ public static void afterClass() throws Exception { service.stop(); } - @Test - public void findByIdElementTest() { + @Before public void setUp() throws Exception { + if (!populated) + //This time out is set because test can be run on slow Android SDK emulator + PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); + + populated = true; + } + + @Test public void findByIdElementTest() { assertNotEquals(null, textId.getAttribute("text")); } - @Test - public void findBySelendroidSelectorTest() { + @Test public void findBySelendroidSelectorTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } - @Test - public void findByElementByNameTest() { + @Test public void findByElementByNameTest() { assertEquals("Accessibility", textName.getText()); } - @Test - public void findByElementByNameAndroidTest() { + @Test public void findByElementByNameAndroidTest() { assertEquals("Accessibility", textNameAndroid.getText()); } - @Test - public void findByElementByNameDefaultTest() { + @Test public void findByElementByNameDefaultTest() { assertEquals("Accessibility", textNameDefault.getText()); } - @Test - public void findByElementByXpathTest() { + @Test public void findByElementByXpathTest() { assertEquals("Accessibility", textXpath.getText()); } - @Test - public void findByElementByIdsTest() { + @Test public void findByElementByIdsTest() { assertNotNull(textIds.getText()); } - @Test - public void findByElementByTestAllTest() { + @Test public void findByElementByTestAllTest() { assertNotNull(textAll.getText()); } - @Test - public void findByElementByTextsAllTest() { + @Test public void findByElementByTextsAllTest() { assertTrue(textsAll.size() > 1); } - @Test - public void findByElementByCalssTest() { + @Test public void findByElementByCalssTest() { assertNotEquals(null, textClass.getAttribute("text")); } - @Test - public void findByElementByTagTest() { + @Test public void findByElementByTagTest() { assertNotEquals(null, textTag.getAttribute("text")); } - @Test - public void findBySelendroidAnnotationOnlyTest() { + @Test public void findBySelendroidAnnotationOnlyTest() { assertNotEquals(null, textSelendroidId.getAttribute("text")); } - @Test - public void findBySelendroidLinkTextTest() { + @Test public void findBySelendroidLinkTextTest() { assertEquals("Accessibility", textLink.getText()); } -} \ No newline at end of file +} diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/TimeOutResetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/TimeOutResetTest.java index 641bc451f..1239a61c9 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/TimeOutResetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/TimeOutResetTest.java @@ -37,106 +37,98 @@ import java.util.concurrent.TimeUnit; public class TimeOutResetTest { - private WebDriver driver; - private final static long ACCEPTABLE_DELTA_MILLS = 1500; - - - @FindAll({@FindBy(className = "ClassWhichDoesNotExist"), - @FindBy(className = "OneAnotherClassWhichDoesNotExist")}) - private List stubElements; + private final static long ACCEPTABLE_DELTA_MILLS = 1500; + private WebDriver driver; + @FindAll({@FindBy(className = "ClassWhichDoesNotExist"), + @FindBy(className = "OneAnotherClassWhichDoesNotExist")}) private List + stubElements; @WithTimeout(time = 5, unit = TimeUnit.SECONDS) @FindAll({@FindBy(className = "ClassWhichDoesNotExist"), - @FindBy(className = "OneAnotherClassWhichDoesNotExist")}) - private List stubElements2; + @FindBy(className = "OneAnotherClassWhichDoesNotExist")}) private List + stubElements2; private TimeOutDuration timeOutDuration; - @Before - public void setUp() throws Exception { - if (Platform.getCurrent().is(Platform.WINDOWS)) { - System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); - } - else { - System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); - } - driver = new ChromeDriver(); - timeOutDuration = new TimeOutDuration(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, - AppiumFieldDecorator.DEFAULT_TIMEUNIT); - PageFactory.initElements(new AppiumFieldDecorator(driver, timeOutDuration), this); - } - - @After - public void tearDown() throws Exception { - driver.quit(); - } - - private static void checkTimeDifference(long expectedTime, - TimeUnit expectedTimeUnit, long currentMillis) { - long expectedMillis = TimeUnit.MILLISECONDS.convert(expectedTime, - expectedTimeUnit); - try{ - Assert.assertEquals(true, - ((currentMillis - expectedMillis) < ACCEPTABLE_DELTA_MILLS) - && ((currentMillis - expectedMillis) >= 0)); - } - catch (Error e){ - String message = String.valueOf(expectedTime) + " " + expectedTimeUnit.toString() + " current duration in millis " + - String.valueOf(currentMillis) + " Failed"; - throw new RuntimeException(message, e); - } - } - - private long getBenchMark(List stubElements) { - long startMark = Calendar.getInstance().getTimeInMillis(); - stubElements.size(); - long endMark = Calendar.getInstance().getTimeInMillis(); - return endMark - startMark; - } - - @Test - public void test() { - checkTimeDifference(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, AppiumFieldDecorator.DEFAULT_TIMEUNIT, - getBenchMark(stubElements)); - System.out.println(String.valueOf(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT) - + " " + AppiumFieldDecorator.DEFAULT_TIMEUNIT.toString() + ": Fine"); - - timeOutDuration.setTime(15500000, TimeUnit.MICROSECONDS); - checkTimeDifference(15500000, TimeUnit.MICROSECONDS, getBenchMark(stubElements)); - System.out.println("Change time: " + String.valueOf(15500000) + " " - + TimeUnit.MICROSECONDS.toString() + ": Fine"); + private static void checkTimeDifference(long expectedTime, TimeUnit expectedTimeUnit, + long currentMillis) { + long expectedMillis = TimeUnit.MILLISECONDS.convert(expectedTime, expectedTimeUnit); + try { + Assert.assertEquals(true, + ((currentMillis - expectedMillis) < ACCEPTABLE_DELTA_MILLS) && ( + (currentMillis - expectedMillis) >= 0)); + } catch (Error e) { + String message = String.valueOf(expectedTime) + " " + expectedTimeUnit.toString() + + " current duration in millis " + + String.valueOf(currentMillis) + " Failed"; + throw new RuntimeException(message, e); + } + } + + @Before public void setUp() throws Exception { + if (Platform.getCurrent().is(Platform.WINDOWS)) { + System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); + } else { + System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); + } + driver = new ChromeDriver(); + timeOutDuration = new TimeOutDuration(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, + AppiumFieldDecorator.DEFAULT_TIMEUNIT); + PageFactory.initElements(new AppiumFieldDecorator(driver, timeOutDuration), this); + } + + @After public void tearDown() throws Exception { + driver.quit(); + } + + private long getBenchMark(List stubElements) { + long startMark = Calendar.getInstance().getTimeInMillis(); + stubElements.size(); + long endMark = Calendar.getInstance().getTimeInMillis(); + return endMark - startMark; + } + + @Test public void test() { + checkTimeDifference(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, + AppiumFieldDecorator.DEFAULT_TIMEUNIT, getBenchMark(stubElements)); + System.out.println( + String.valueOf(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT) + " " + + AppiumFieldDecorator.DEFAULT_TIMEUNIT.toString() + ": Fine"); + + timeOutDuration.setTime(15500000, TimeUnit.MICROSECONDS); + checkTimeDifference(15500000, TimeUnit.MICROSECONDS, getBenchMark(stubElements)); + System.out.println( + "Change time: " + String.valueOf(15500000) + " " + TimeUnit.MICROSECONDS.toString() + + ": Fine"); timeOutDuration.setTime(3, TimeUnit.SECONDS); - checkTimeDifference(3, TimeUnit.SECONDS, getBenchMark(stubElements)); - System.out.println("Change time: " + String.valueOf(3) + " " - + TimeUnit.SECONDS.toString() + ": Fine"); + checkTimeDifference(3, TimeUnit.SECONDS, getBenchMark(stubElements)); + System.out.println( + "Change time: " + String.valueOf(3) + " " + TimeUnit.SECONDS.toString() + ": Fine"); - } + } - @Test - public void test2() { - checkTimeDifference(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, AppiumFieldDecorator.DEFAULT_TIMEUNIT, - getBenchMark(stubElements)); - System.out.println(String.valueOf(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT) - + " " + AppiumFieldDecorator.DEFAULT_TIMEUNIT.toString() + ": Fine"); + @Test public void test2() { + checkTimeDifference(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT, + AppiumFieldDecorator.DEFAULT_TIMEUNIT, getBenchMark(stubElements)); + System.out.println( + String.valueOf(AppiumFieldDecorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT) + " " + + AppiumFieldDecorator.DEFAULT_TIMEUNIT.toString() + ": Fine"); - checkTimeDifference(5, TimeUnit.SECONDS, - getBenchMark(stubElements2)); - System.out.println(String.valueOf(5) - + " " + TimeUnit.SECONDS.toString() + ": Fine"); + checkTimeDifference(5, TimeUnit.SECONDS, getBenchMark(stubElements2)); + System.out.println(String.valueOf(5) + " " + TimeUnit.SECONDS.toString() + ": Fine"); timeOutDuration.setTime(15500000, TimeUnit.MICROSECONDS); checkTimeDifference(15500000, TimeUnit.MICROSECONDS, getBenchMark(stubElements)); - System.out.println("Change time: " + String.valueOf(15500000) + " " - + TimeUnit.MICROSECONDS.toString() + ": Fine"); + System.out.println( + "Change time: " + String.valueOf(15500000) + " " + TimeUnit.MICROSECONDS.toString() + + ": Fine"); - checkTimeDifference(5, TimeUnit.SECONDS, - getBenchMark(stubElements2)); - System.out.println(String.valueOf(5) - + " " + TimeUnit.SECONDS.toString() + ": Fine"); + checkTimeDifference(5, TimeUnit.SECONDS, getBenchMark(stubElements2)); + System.out.println(String.valueOf(5) + " " + TimeUnit.SECONDS.toString() + ": Fine"); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java index 5805b7369..3b1b36a65 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/iOSPageObjectTest.java @@ -37,296 +37,237 @@ public class iOSPageObjectTest { - private static WebDriver driver; - private static AppiumDriverLocalService service; - private boolean populated = false; + private static WebDriver driver; + private static AppiumDriverLocalService service; + private boolean populated = false; - @FindBy(className = "UIAButton") - private List uiButtons; + @FindBy(className = "UIAButton") private List uiButtons; - @FindBy(className = "UIAButton") - private List iosUIButtons; + @FindBy(className = "UIAButton") private List iosUIButtons; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List iosUIAutomatorButtons; + @iOSFindBy(uiAutomator = ".elements()[0]") private List iosUIAutomatorButtons; - @iOSFindBy(uiAutomator = ".elements()[0]") - @AndroidFindBy(className = "android.widget.TextView") - private List androidOriOsTextViews; + @iOSFindBy(uiAutomator = ".elements()[0]") @AndroidFindBy(className = "android.widget.TextView") + private List androidOriOsTextViews; - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") - private List androidUIAutomatorViews; + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") + private List androidUIAutomatorViews; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List mobileButtons; + @iOSFindBy(uiAutomator = ".elements()[0]") private List mobileButtons; - @FindBy(className = "UIAButton") - private List mobiletFindBy_Buttons; + @FindBy(className = "UIAButton") private List mobiletFindBy_Buttons; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List remoteElementViews; + @iOSFindBy(uiAutomator = ".elements()[0]") private List remoteElementViews; - @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) - private List chainElementViews; + @AndroidFindBys({ + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), + @AndroidFindBy(className = "android.widget.TextView")}) private List + chainElementViews; - @FindBy(className = "UIAButton") - private WebElement uiButton; + @FindBy(className = "UIAButton") private WebElement uiButton; - @FindBy(className = "UIAButton") - private WebElement iosUIButton; + @FindBy(className = "UIAButton") private WebElement iosUIButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private WebElement iosUIAutomatorButton; + @iOSFindBy(uiAutomator = ".elements()[0]") private WebElement iosUIAutomatorButton; - @AndroidFindBy(className = "android.widget.TextView") - @iOSFindBy(uiAutomator = ".elements()[0]") - private WebElement androidOriOsTextView; + @AndroidFindBy(className = "android.widget.TextView") @iOSFindBy(uiAutomator = ".elements()[0]") + private WebElement androidOriOsTextView; - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") - private WebElement androidUIAutomatorView; + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/text1\")") + private WebElement androidUIAutomatorView; - @iOSFindBy(uiAutomator = ".elements()[0]") - private MobileElement mobileButton; + @iOSFindBy(uiAutomator = ".elements()[0]") private MobileElement mobileButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private TouchableElement touchableButton; + @iOSFindBy(uiAutomator = ".elements()[0]") private TouchableElement touchableButton; - @iOSFindBy(uiAutomator = ".elements()[0]") - private List touchableButtons; + @iOSFindBy(uiAutomator = ".elements()[0]") private List touchableButtons; - @FindBy(className = "UIAButton") - private MobileElement mobiletFindBy_Button; + @FindBy(className = "UIAButton") private MobileElement mobiletFindBy_Button; - @iOSFindBy(uiAutomator = ".elements()[0]") - private RemoteWebElement remotetextVieW; + @iOSFindBy(uiAutomator = ".elements()[0]") private RemoteWebElement remotetextVieW; - @AndroidFindBys({ - @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), - @AndroidFindBy(className = "android.widget.TextView") - }) - private WebElement chainElementView; - - @iOSFindBy(uiAutomator = ".elements()[0]") - private IOSElement iosButton; - - @iOSFindBy(uiAutomator = ".elements()[0]") - private List iosButtons; - - @iOSFindAll({ - @iOSFindBy(id = "ComputeSumButton_Test"), - @iOSFindBy(xpath = "//*[@name = \"ComputeSumButton\"]") //it is real locator - }) - private WebElement findAllElement; - - @iOSFindAll({ - @iOSFindBy(id = "ComputeSumButton_Test"), - @iOSFindBy(xpath = "//*[@name = \"ComputeSumButton\"]") //it is real locator - }) - private List findAllElements; - - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private List elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - @AndroidFindBy(className = "android.widget.TextView") - @FindBy(css = "e.e1.e2") - private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; - - - @BeforeClass - public static void beforeClass() throws Exception { - service = AppiumDriverLocalService.buildDefaultService(); - service.start(); - - File appDir = new File("src/test/java/io/appium/java_client"); - File app = new File(appDir, "TestApp.app.zip"); - DesiredCapabilities capabilities = new DesiredCapabilities(); - capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); - capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1"); - capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); - capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); - driver = new IOSDriver(service.getUrl(), capabilities); - } - - @SuppressWarnings("rawtypes") - @Before - public void setUp() throws Exception { - if (!populated) - PageFactory.initElements(new AppiumFieldDecorator(driver), this); - - populated = true; - } - - @AfterClass - public static void afterClass() throws Exception { - if (driver != null) - driver.quit(); - - if (service != null) - service.stop(); - } - - @Test - public void findByElementsTest() { - Assert.assertNotEquals(0, uiButtons.size()); - } - - @Test - public void findByElementTest() { - Assert.assertNotEquals(null, uiButton.getText()); - } - - - @Test - public void iOSFindByElementsTest(){ - Assert.assertNotEquals(0, iosUIButtons.size()); - } - - @Test - public void iosFindByElementTest(){ - Assert.assertNotEquals(null, iosUIButton.getText()); - } - - @Test - public void checkThatElementsWereNotFoundByAndroidUIAutomator(){ - Assert.assertEquals(0, androidUIAutomatorViews.size()); - } - - @Test - public void checkThatElementWasNotFoundByAndroidUIAutomator(){ - NoSuchElementException nsee = null; - try{ - androidUIAutomatorView.getText(); - } - catch (Exception e){ - nsee = (NoSuchElementException) e; - } - Assert.assertNotNull(nsee); - } - - @Test - public void androidOrIOSFindByElementsTest(){ - Assert.assertNotEquals(0, androidOriOsTextViews.size()); - } - - @Test - public void androidOrIOSFindByElementTest(){ - Assert.assertNotEquals(null, androidOriOsTextView.getText()); - } - - @Test - public void iOSFindByUIAutomatorElementsTest(){ - Assert.assertNotEquals(0, iosUIAutomatorButtons.size()); - } - - @Test - public void iOSFindByUIAutomatorElementTest(){ - Assert.assertNotEquals(null, iosUIAutomatorButton.getText()); - } - - @Test - public void areMobileElementsTest(){ - Assert.assertNotEquals(0, mobileButtons.size()); - } - - @Test - public void isMobileElementTest(){ - Assert.assertNotEquals(null, mobileButton.getText()); - } - - @Test - public void areMobileElements_FindByTest(){ - Assert.assertNotEquals(0, mobiletFindBy_Buttons.size()); - } - - @Test - public void isMobileElement_FindByTest(){ - Assert.assertNotEquals(null, mobiletFindBy_Button.getText()); - } - - @Test - public void areRemoteElementsTest(){ - Assert.assertNotEquals(0, remoteElementViews.size()); - } - - @Test - public void isRemoteElementTest(){ - Assert.assertNotEquals(null, remotetextVieW.getText()); - } - - @Test - public void checkThatElementsWereNotFoundByAndroidUIAutomator_Chain(){ - Assert.assertEquals(0, chainElementViews.size()); - } - - @Test - public void checkThatElementWasNotFoundByAndroidUIAutomator_Chain(){ - NoSuchElementException nsee = null; - try{ - chainElementView.getText(); - } - catch (Exception e){ - nsee = (NoSuchElementException) e; - } - Assert.assertNotNull(nsee); - } - - @Test - public void isIOSElementTest(){ - Assert.assertNotEquals(null, iosButton.getText()); - } - - @Test - public void areIOSElements_FindByTest(){ - Assert.assertNotEquals(0, iosButtons.size()); - } - - @Test - public void findAllElementsTest(){ - Assert.assertNotEquals(0, findAllElements.size()); - } - - @Test - public void findAllElementTest(){ - Assert.assertNotEquals(null, findAllElement.getText()); - } - - @Test - public void isTouchAbleElement(){ - Assert.assertNotEquals(null, touchableButton.getText()); - } - - @Test - public void areTouchAbleElements(){ - Assert.assertNotEquals(0, touchableButtons.size()); - } - - @Test - public void isTheFieldIOSElement(){ - @SuppressWarnings("unused") - IOSElement iOSElement = (IOSElement) mobileButton; //declared as MobileElement - iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement - iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement - iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy(){ - try { - Assert.assertNotEquals(null, elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); - } - catch (NoSuchElementException ignored){ - return; - } - throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); - } - - @Test - public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List(){ - Assert.assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); - } -} \ No newline at end of file + @AndroidFindBys({ + @AndroidFindBy(uiAutomator = "new UiSelector().resourceId(\"android:id/list\")"), + @AndroidFindBy(className = "android.widget.TextView")}) private WebElement chainElementView; + + @iOSFindBy(uiAutomator = ".elements()[0]") private IOSElement iosButton; + + @iOSFindBy(uiAutomator = ".elements()[0]") private List iosButtons; + + @iOSFindAll({@iOSFindBy(id = "ComputeSumButton_Test"), + @iOSFindBy(xpath = "//*[@name = \"ComputeSumButton\"]") //it is real locator + }) private WebElement findAllElement; + + @iOSFindAll({@iOSFindBy(id = "ComputeSumButton_Test"), + @iOSFindBy(xpath = "//*[@name = \"ComputeSumButton\"]") //it is real locator + }) private List findAllElements; + + @AndroidFindBy(className = "android.widget.TextView") @FindBy(css = "e.e1.e2") + private List elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + + @AndroidFindBy(className = "android.widget.TextView") @FindBy(css = "e.e1.e2") + private WebElement elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy; + + + @BeforeClass public static void beforeClass() throws Exception { + service = AppiumDriverLocalService.buildDefaultService(); + service.start(); + + File appDir = new File("src/test/java/io/appium/java_client"); + File app = new File(appDir, "TestApp.app.zip"); + DesiredCapabilities capabilities = new DesiredCapabilities(); + capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); + capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1"); + capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); + capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); + driver = new IOSDriver(service.getUrl(), capabilities); + } + + @AfterClass public static void afterClass() throws Exception { + if (driver != null) + driver.quit(); + + if (service != null) + service.stop(); + } + + @SuppressWarnings("rawtypes") @Before public void setUp() throws Exception { + if (!populated) + PageFactory.initElements(new AppiumFieldDecorator(driver), this); + + populated = true; + } + + @Test public void findByElementsTest() { + Assert.assertNotEquals(0, uiButtons.size()); + } + + @Test public void findByElementTest() { + Assert.assertNotEquals(null, uiButton.getText()); + } + + + @Test public void iOSFindByElementsTest() { + Assert.assertNotEquals(0, iosUIButtons.size()); + } + + @Test public void iosFindByElementTest() { + Assert.assertNotEquals(null, iosUIButton.getText()); + } + + @Test public void checkThatElementsWereNotFoundByAndroidUIAutomator() { + Assert.assertEquals(0, androidUIAutomatorViews.size()); + } + + @Test public void checkThatElementWasNotFoundByAndroidUIAutomator() { + NoSuchElementException nsee = null; + try { + androidUIAutomatorView.getText(); + } catch (Exception e) { + nsee = (NoSuchElementException) e; + } + Assert.assertNotNull(nsee); + } + + @Test public void androidOrIOSFindByElementsTest() { + Assert.assertNotEquals(0, androidOriOsTextViews.size()); + } + + @Test public void androidOrIOSFindByElementTest() { + Assert.assertNotEquals(null, androidOriOsTextView.getText()); + } + + @Test public void iOSFindByUIAutomatorElementsTest() { + Assert.assertNotEquals(0, iosUIAutomatorButtons.size()); + } + + @Test public void iOSFindByUIAutomatorElementTest() { + Assert.assertNotEquals(null, iosUIAutomatorButton.getText()); + } + + @Test public void areMobileElementsTest() { + Assert.assertNotEquals(0, mobileButtons.size()); + } + + @Test public void isMobileElementTest() { + Assert.assertNotEquals(null, mobileButton.getText()); + } + + @Test public void areMobileElements_FindByTest() { + Assert.assertNotEquals(0, mobiletFindBy_Buttons.size()); + } + + @Test public void isMobileElement_FindByTest() { + Assert.assertNotEquals(null, mobiletFindBy_Button.getText()); + } + + @Test public void areRemoteElementsTest() { + Assert.assertNotEquals(0, remoteElementViews.size()); + } + + @Test public void isRemoteElementTest() { + Assert.assertNotEquals(null, remotetextVieW.getText()); + } + + @Test public void checkThatElementsWereNotFoundByAndroidUIAutomator_Chain() { + Assert.assertEquals(0, chainElementViews.size()); + } + + @Test public void checkThatElementWasNotFoundByAndroidUIAutomator_Chain() { + NoSuchElementException nsee = null; + try { + chainElementView.getText(); + } catch (Exception e) { + nsee = (NoSuchElementException) e; + } + Assert.assertNotNull(nsee); + } + + @Test public void isIOSElementTest() { + Assert.assertNotEquals(null, iosButton.getText()); + } + + @Test public void areIOSElements_FindByTest() { + Assert.assertNotEquals(0, iosButtons.size()); + } + + @Test public void findAllElementsTest() { + Assert.assertNotEquals(0, findAllElements.size()); + } + + @Test public void findAllElementTest() { + Assert.assertNotEquals(null, findAllElement.getText()); + } + + @Test public void isTouchAbleElement() { + Assert.assertNotEquals(null, touchableButton.getText()); + } + + @Test public void areTouchAbleElements() { + Assert.assertNotEquals(0, touchableButtons.size()); + } + + @Test public void isTheFieldIOSElement() { + @SuppressWarnings("unused") IOSElement iOSElement = + (IOSElement) mobileButton; //declared as MobileElement + iOSElement = (IOSElement) iosUIAutomatorButton; //declared as WebElement + iOSElement = (IOSElement) remotetextVieW; //declared as RemoteWebElement + iOSElement = (IOSElement) touchableButton; //declared as TouchABLEElement + } + + @Test public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy() { + try { + Assert.assertNotEquals(null, + elementWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.getAttribute("text")); + } catch (NoSuchElementException ignored) { + return; + } + throw new RuntimeException(NoSuchElementException.class.getName() + " has been expected."); + } + + @Test public void checkThatTestWillNotBeFailedBecauseOfInvalidFindBy_List() { + Assert + .assertEquals(0, elementsWhenAndroidLocatorIsNotDefinedAndThereIsInvalidFindBy.size()); + } +} diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/AndroidOverrideWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/AndroidOverrideWidgetTest.java index 812fe996f..c134cfc25 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/AndroidOverrideWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/AndroidOverrideWidgetTest.java @@ -22,14 +22,13 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class AndroidOverrideWidgetTest implements WidgetTest{ +public class AndroidOverrideWidgetTest implements WidgetTest { private static AndroidDriver driver; private static AppiumDriverLocalService service; private static RottenTomatoes rottenTomatoes; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); @@ -41,17 +40,12 @@ public static void beforeClass() throws Exception { driver = new AndroidDriver<>(service.getUrl(), capabilities); rottenTomatoes = new RottenTomatoes(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoes); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoes); } - @Before - public void setUp() throws Exception { - if (driver != null) - driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); - } - - @AfterClass - public static void afterClass() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) driver.quit(); @@ -59,9 +53,12 @@ public static void afterClass() throws Exception { service.stop(); } - @Test - @Override - public void checkACommonWidget() { + @Before public void setUp() throws Exception { + if (driver != null) + driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); + } + + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -73,9 +70,7 @@ public void checkACommonWidget() { assertTrue(movie.getSelfReference().getClass().equals(AndroidMovie.class)); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -88,9 +83,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -102,13 +95,10 @@ public void checkAnExtendedWidget() { assertTrue(movie.getSelfReference().getClass().equals(AnnotatedAndroidMovie.class)); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -117,8 +107,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/HtmlOverrideWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/HtmlOverrideWidgetTest.java index 3bf8ec42a..5ccd0f698 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/HtmlOverrideWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/HtmlOverrideWidgetTest.java @@ -21,44 +21,42 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class HtmlOverrideWidgetTest implements WidgetTest{ +public class HtmlOverrideWidgetTest implements WidgetTest { private static ChromeDriver driver; private static RottenTomatoes rottenTomatoes; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { if (Platform.getCurrent().is(Platform.WINDOWS)) { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); - } - else { + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); + } else { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); } driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); rottenTomatoes = new RottenTomatoes(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoes); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoes); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) - driver.get( new File("src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html").toURI().toString()); + driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { + @Before public void setUp() throws Exception { if (driver != null) - driver.quit(); + driver.get( + new File("src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html").toURI() + .toString()); } - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -70,9 +68,7 @@ public void checkACommonWidget() { assertTrue(movie.getSelfReference().getClass().equals(HtmlMovie.class)); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -85,9 +81,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -99,13 +93,10 @@ public void checkAnExtendedWidget() { assertTrue(movie.getSelfReference().getClass().equals(AnnotatedHtmlMovie.class)); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -114,8 +105,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/IOSOverrideWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/IOSOverrideWidgetTest.java index c189057f0..824d199e8 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/IOSOverrideWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/IOSOverrideWidgetTest.java @@ -19,20 +19,23 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class IOSOverrideWidgetTest implements WidgetTest{ +public class IOSOverrideWidgetTest implements WidgetTest { - private IOSDriver driver; private static AppiumDriverLocalService service; private static RottenTomatoes rottenTomatoes; + private IOSDriver driver; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "RottenTomatoes.zip"); @@ -44,24 +47,17 @@ public void setUp() throws Exception { driver = new IOSDriver<>(service.getUrl(), capabilities); rottenTomatoes = new RottenTomatoes(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoes); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoes); } - @After - public void tearDown() { + @After public void tearDown() { if (driver != null) driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { - if (service != null) - service.stop(); - } - - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -73,9 +69,7 @@ public void checkACommonWidget() { assertTrue(movie.getSelfReference().getClass().equals(IOSMovie.class)); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -88,9 +82,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -102,13 +94,10 @@ public void checkAnExtendedWidget() { assertTrue(movie.getSelfReference().getClass().equals(AnnotatedIOSMovie.class)); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -117,8 +106,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movie.java index 4bd530057..4893d67dc 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movie.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory.Widget; import org.openqa.selenium.WebElement; -public abstract class Movie extends Widget{ +public abstract class Movie extends Widget { protected Movie(WebElement element) { super(element); } @@ -16,8 +16,7 @@ protected Movie(WebElement element) { public abstract void goToReview(); - @Override - public Movie getSelfReference() { + @Override public Movie getSelfReference() { return (Movie) super.getSelfReference(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movies.java index f5209987e..8607f61d2 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Movies.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory.Widget; import org.openqa.selenium.WebElement; -public abstract class Movies extends Widget{ +public abstract class Movies extends Widget { protected Movies(WebElement element) { super(element); @@ -13,8 +13,7 @@ protected Movies(WebElement element) { public abstract Movie getMovie(int index); - @Override - public Movies getSelfReference() { + @Override public Movies getSelfReference() { return (Movies) super.getSelfReference(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Review.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Review.java index 2e53731bb..27483ed91 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Review.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/Review.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory.Widget; import org.openqa.selenium.WebElement; -public abstract class Review extends Widget{ +public abstract class Review extends Widget { protected Review(WebElement element) { super(element); @@ -17,8 +17,7 @@ protected Review(WebElement element) { public abstract Object getPoster(); - @Override - public Review getSelfReference() { + @Override public Review getSelfReference() { return (Review) super.getSelfReference(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/RottenTomatoes.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/RottenTomatoes.java index 89aefbe17..6d908d793 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/RottenTomatoes.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/RottenTomatoes.java @@ -35,66 +35,60 @@ public class RottenTomatoes { @FindBy(id = "movies-collection") @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") - @SelendroidFindBy(id = "lvMovies") - @iOSFindBy(className = "UIATableView") + @SelendroidFindBy(id = "lvMovies") @iOSFindBy(className = "UIATableView") @OverrideWidget(html = HtmlMovies.class, selendroid = SelendroidMovies.class, - androidUIAutomator = AndroidMovies.class, iOSUIAutomation = IOSMovies.class) - private Movies simpleMovies; + androidUIAutomator = AndroidMovies.class, iOSUIAutomation = IOSMovies.class) private Movies + simpleMovies; @AndroidFindBys({@AndroidFindBy(id = "android:id/content"), - @AndroidFindBy(className = "android.widget.RelativeLayout")}) - @FindBy(id = "main_container") + @AndroidFindBy(className = "android.widget.RelativeLayout")}) @FindBy(id = "main_container") @SelendroidFindBy(className = "android.widget.RelativeLayout") @iOSFindBy(className = "UIAWindow") @OverrideWidget(html = HtmlReview.class, selendroid = SelendroidReview.class, - androidUIAutomator = AndroidReview.class, iOSUIAutomation = IOSReview.class) - private Review simpleReview; + androidUIAutomator = AndroidReview.class, iOSUIAutomation = IOSReview.class) private Review + simpleReview; @OverrideWidget(html = AnnotatedHtmlMovies.class, selendroid = AnnotatedSelendroidMovies.class, - androidUIAutomator = AnnotatedAndroidMovies.class, iOSUIAutomation = AnnotatedIOSMovies.class) + androidUIAutomator = AnnotatedAndroidMovies.class, iOSUIAutomation = AnnotatedIOSMovies.class) private Movies annotatedMovies; @OverrideWidget(html = AnnotatedHtmlReview.class, selendroid = AnnotatedSelendroidReview.class, - androidUIAutomator = AnnotatedAndroidReview.class, iOSUIAutomation = AnnotatedIOSReview.class) + androidUIAutomator = AnnotatedAndroidReview.class, iOSUIAutomation = AnnotatedIOSReview.class) private Review annotatedReview; @OverrideWidget(html = ExtendedHtmlMovies.class, selendroid = ExtendedSelendroidMovies.class, - androidUIAutomator = ExtendedAndroidMovies.class, iOSUIAutomation = ExtendedIOSMovies.class) + androidUIAutomator = ExtendedAndroidMovies.class, iOSUIAutomation = ExtendedIOSMovies.class) private Movies extendedMovies; @OverrideWidget(html = ExtendedHtmlReview.class, selendroid = ExtendedSelendroidReview.class, - androidUIAutomator = ExtendedAndroidReview.class, iOSUIAutomation = ExtendedIOSReview.class) + androidUIAutomator = ExtendedAndroidReview.class, iOSUIAutomation = ExtendedIOSReview.class) private Review extendedReview; - @FindBy(id = "Fake_ID_For_All_Platforms") - @AndroidFindBy(id = "Fake_ID_For_All_Platforms") - @SelendroidFindBy(id = "Fake_ID_For_All_Platforms") - @iOSFindBy(id = "Fake_ID_For_All_Platforms") + @FindBy(id = "Fake_ID_For_All_Platforms") @AndroidFindBy(id = "Fake_ID_For_All_Platforms") + @SelendroidFindBy(id = "Fake_ID_For_All_Platforms") @iOSFindBy(id = "Fake_ID_For_All_Platforms") @OverrideWidget(html = ExtendedHtmlMovies.class, selendroid = ExtendedSelendroidMovies.class, - androidUIAutomator = ExtendedAndroidMovies.class, iOSUIAutomation = ExtendedIOSMovies.class) + androidUIAutomator = ExtendedAndroidMovies.class, iOSUIAutomation = ExtendedIOSMovies.class) private Movies fakeMovies; - @FindBy(id = "Fake_ID_For_All_Platforms") - @AndroidFindBy(id = "Fake_ID_For_All_Platforms") - @SelendroidFindBy(id = "Fake_ID_For_All_Platforms") - @iOSFindBy(id = "Fake_ID_For_All_Platforms") + @FindBy(id = "Fake_ID_For_All_Platforms") @AndroidFindBy(id = "Fake_ID_For_All_Platforms") + @SelendroidFindBy(id = "Fake_ID_For_All_Platforms") @iOSFindBy(id = "Fake_ID_For_All_Platforms") @OverrideWidget(html = ExtendedHtmlReview.class, selendroid = ExtendedSelendroidReview.class, - androidUIAutomator = ExtendedAndroidReview.class, iOSUIAutomation = ExtendedIOSReview.class) + androidUIAutomator = ExtendedAndroidReview.class, iOSUIAutomation = ExtendedIOSReview.class) private Review fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -102,15 +96,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedReview.title())); assertTrue(!StringUtils.isBlank(annotatedReview.score())); assertTrue(!StringUtils.isBlank(annotatedReview.info())); @@ -118,15 +112,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedReview.title())); assertTrue(!StringUtils.isBlank(extendedReview.score())); assertTrue(!StringUtils.isBlank(extendedReview.info())); @@ -135,11 +129,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/SelendroidOverrideWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/SelendroidOverrideWidgetTest.java index ec423c9f6..3138cd9df 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/SelendroidOverrideWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/SelendroidOverrideWidgetTest.java @@ -19,22 +19,24 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class SelendroidOverrideWidgetTest implements WidgetTest{ +public class SelendroidOverrideWidgetTest implements WidgetTest { private static int SELENDROID_PORT = 9999; - - private AndroidDriver driver; private static AppiumDriverLocalService service; + private AndroidDriver driver; private RottenTomatoes rottenTomatoes; private TimeOutDuration duration; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "android-rottentomatoes-demo-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); @@ -50,20 +52,11 @@ public void setUp() throws Exception { PageFactory.initElements(new AppiumFieldDecorator(driver, duration), rottenTomatoes); } - @After - public void tearDown() throws Exception { + @After public void tearDown() throws Exception { driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { - if (service != null) - service.stop(); - } - - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -74,9 +67,7 @@ public void checkACommonWidget() { rottenTomatoes.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -88,9 +79,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -101,14 +90,11 @@ public void checkAnExtendedWidget() { rottenTomatoes.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { duration.setTime(5); try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -117,8 +103,7 @@ public void checkTheLocatorOverridingOnAWidget() { driver.getPageSource(); //forcing the refreshing hierarchy try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/AndroidWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/AndroidWidgetTest.java index 178669414..f42d90ecb 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/AndroidWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/AndroidWidgetTest.java @@ -22,14 +22,13 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class AndroidWidgetTest implements WidgetTest{ +public class AndroidWidgetTest implements WidgetTest { private static AndroidDriver driver; private static AppiumDriverLocalService service; private static RottenTomatoesApp rottenTomatoesApp; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); @@ -41,17 +40,12 @@ public static void beforeClass() throws Exception { driver = new AndroidDriver<>(service.getUrl(), capabilities); rottenTomatoesApp = new RottenTomatoesApp(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoesApp); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoesApp); } - @Before - public void setUp() throws Exception { - if (driver != null) - driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); - } - - @AfterClass - public static void afterClass() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) driver.quit(); @@ -59,9 +53,12 @@ public static void afterClass() throws Exception { service.stop(); } - @Test - @Override - public void checkACommonWidget() { + @Before public void setUp() throws Exception { + if (driver != null) + driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); + } + + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoesApp.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoesApp.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -72,9 +69,7 @@ public void checkACommonWidget() { rottenTomatoesApp.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoesApp.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -86,9 +81,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoesApp.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -99,13 +92,10 @@ public void checkAnExtendedWidget() { rottenTomatoesApp.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoesApp.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -114,8 +104,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoesApp.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/RottenTomatoesApp.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/RottenTomatoesApp.java index 41c9f6653..d3ac5db38 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/RottenTomatoesApp.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/RottenTomatoesApp.java @@ -2,13 +2,13 @@ import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AndroidFindBys; +import io.appium.java_client.pagefactory_tests.widgets.Movie; import io.appium.java_client.pagefactory_tests.widgets.android.annotated.AnnotatedAndroidMovies; import io.appium.java_client.pagefactory_tests.widgets.android.annotated.AnnotatedAndroidReview; import io.appium.java_client.pagefactory_tests.widgets.android.extended.ExtendedAndroidMovies; import io.appium.java_client.pagefactory_tests.widgets.android.extended.ExtendedAndroidReview; import io.appium.java_client.pagefactory_tests.widgets.android.simple.AndroidMovies; import io.appium.java_client.pagefactory_tests.widgets.android.simple.AndroidReview; -import io.appium.java_client.pagefactory_tests.widgets.Movie; import org.apache.commons.lang3.StringUtils; import static org.junit.Assert.assertTrue; @@ -19,12 +19,12 @@ */ public class RottenTomatoesApp { - @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") - private AndroidMovies simpleMovies; + @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") private AndroidMovies + simpleMovies; @AndroidFindBys({@AndroidFindBy(id = "android:id/content"), - @AndroidFindBy(className = "android.widget.RelativeLayout")}) - private AndroidReview simpleReview; + @AndroidFindBy(className = "android.widget.RelativeLayout")}) private AndroidReview + simpleReview; private AnnotatedAndroidMovies annotatedAndroidMovies; @@ -34,22 +34,20 @@ public class RottenTomatoesApp { private ExtendedAndroidReview extendedAndroidReview; - @AndroidFindBy(id = "fakeId") - private ExtendedAndroidMovies fakeMovies; + @AndroidFindBy(id = "fakeId") private ExtendedAndroidMovies fakeMovies; - @AndroidFindBy(id = "fakeId") - private ExtendedAndroidReview fakeReview; + @AndroidFindBy(id = "fakeId") private ExtendedAndroidReview fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -57,15 +55,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedAndroidMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedAndroidMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedAndroidReview.title())); assertTrue(!StringUtils.isBlank(annotatedAndroidReview.score())); assertTrue(!StringUtils.isBlank(annotatedAndroidReview.info())); @@ -73,15 +71,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedAndroidMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedAndroidMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedAndroidReview.title())); assertTrue(!StringUtils.isBlank(extendedAndroidReview.score())); assertTrue(!StringUtils.isBlank(extendedAndroidReview.info())); @@ -90,11 +88,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovie.java index f243855e8..bc7106b7a 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovie.java @@ -4,8 +4,8 @@ import io.appium.java_client.pagefactory_tests.widgets.android.simple.AndroidMovie; import org.openqa.selenium.WebElement; -@AndroidFindBy(className = "android.widget.RelativeLayout") -public class AnnotatedAndroidMovie extends AndroidMovie{ +@AndroidFindBy(className = "android.widget.RelativeLayout") public class AnnotatedAndroidMovie + extends AndroidMovie { protected AnnotatedAndroidMovie(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovies.java index 7bfebc6f6..add9bb54d 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidMovies.java @@ -8,7 +8,7 @@ import java.util.List; @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") -public class AnnotatedAndroidMovies extends Movies{ +public class AnnotatedAndroidMovies extends Movies { List movieList; @@ -21,13 +21,11 @@ protected AnnotatedAndroidMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidReview.java index 64b60def6..b68e0158e 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/annotated/AnnotatedAndroidReview.java @@ -6,8 +6,8 @@ import org.openqa.selenium.WebElement; @AndroidFindBys({@AndroidFindBy(id = "android:id/content"), - @AndroidFindBy(className = "android.widget.RelativeLayout")}) -public class AnnotatedAndroidReview extends AndroidReview{ + @AndroidFindBy(className = "android.widget.RelativeLayout")}) +public class AnnotatedAndroidReview extends AndroidReview { protected AnnotatedAndroidReview(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidMovies.java index f1cbf77a5..6b91a9e17 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidMovies.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory_tests.widgets.android.annotated.AnnotatedAndroidMovies; import org.openqa.selenium.WebElement; -public class ExtendedAndroidMovies extends AnnotatedAndroidMovies{ +public class ExtendedAndroidMovies extends AnnotatedAndroidMovies { protected ExtendedAndroidMovies(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidReview.java index 4eb0c1863..1fc9891e4 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/extended/ExtendedAndroidReview.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory_tests.widgets.android.annotated.AnnotatedAndroidReview; import org.openqa.selenium.WebElement; -public class ExtendedAndroidReview extends AnnotatedAndroidReview{ +public class ExtendedAndroidReview extends AnnotatedAndroidReview { protected ExtendedAndroidReview(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovie.java index cc86daf1c..29a48156f 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovie.java @@ -5,38 +5,33 @@ import io.appium.java_client.pagefactory_tests.widgets.Movie; import org.openqa.selenium.WebElement; -public class AndroidMovie extends Movie{ +public class AndroidMovie extends Movie { - @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") - private AndroidElement title; + @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") private AndroidElement + title; @AndroidFindBy(uiAutomator = "resourceId(\"com.codepath.example.rottentomatoes:id/tvCriticsScore\")") private AndroidElement score; - @AndroidFindBy(accessibility = "poster image") - private AndroidElement poster; + @AndroidFindBy(accessibility = "poster image") private AndroidElement poster; protected AndroidMovie(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } - @Override - public void goToReview() { + @Override public void goToReview() { ((AndroidElement) getWrappedElement()).tap(1, 1500); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovies.java index 9380cce58..1edec01d4 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidMovies.java @@ -8,10 +8,9 @@ import java.util.List; -public class AndroidMovies extends Movies{ +public class AndroidMovies extends Movies { - @AndroidFindBy(className = "android.widget.RelativeLayout") - List movieList; + @AndroidFindBy(className = "android.widget.RelativeLayout") List movieList; /* There could be additional behavior. @@ -22,13 +21,11 @@ protected AndroidMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidReview.java index f5365febe..aaf13bed3 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/android/simple/AndroidReview.java @@ -6,16 +6,16 @@ import io.appium.java_client.pagefactory_tests.widgets.Review; import org.openqa.selenium.WebElement; -public class AndroidReview extends Review{ +public class AndroidReview extends Review { - @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") - private AndroidElement title; + @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") private AndroidElement + title; @AndroidFindBy(uiAutomator = "resourceId(\"com.codepath.example.rottentomatoes:id/tvCriticsScore\")") private AndroidElement score; - @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvSynopsis") - private AndroidElement synopsis; + @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvSynopsis") private AndroidElement + synopsis; @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/ivPosterImage") private AndroidElement poster; @@ -25,23 +25,19 @@ protected AndroidReview(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public String info() { + @Override public String info() { return synopsis.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/AndroidCombinedWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/AndroidCombinedWidgetTest.java index 5fb227ebb..2a844b437 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/AndroidCombinedWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/AndroidCombinedWidgetTest.java @@ -22,14 +22,13 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class AndroidCombinedWidgetTest implements WidgetTest{ +public class AndroidCombinedWidgetTest implements WidgetTest { private static AndroidDriver driver; private static AppiumDriverLocalService service; private static RottenTomatoesAppWithCombinedWidgets rottenTomatoes; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); @@ -41,17 +40,12 @@ public static void beforeClass() throws Exception { driver = new AndroidDriver<>(service.getUrl(), capabilities); rottenTomatoes = new RottenTomatoesAppWithCombinedWidgets(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoes); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoes); } - @Before - public void setUp() throws Exception { - if (driver != null) - driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); - } - - @AfterClass - public static void afterClass() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) driver.quit(); @@ -59,9 +53,12 @@ public static void afterClass() throws Exception { service.stop(); } - @Test - @Override - public void checkACommonWidget() { + @Before public void setUp() throws Exception { + if (driver != null) + driver.startActivity("com.codepath.example.rottentomatoes", "BoxOfficeActivity"); + } + + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -72,9 +69,7 @@ public void checkACommonWidget() { rottenTomatoes.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -86,9 +81,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -99,13 +92,10 @@ public void checkAnExtendedWidget() { rottenTomatoes.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -114,8 +104,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/HtmlCombinedWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/HtmlCombinedWidgetTest.java index 34e5b0c78..3b3ad0ed8 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/HtmlCombinedWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/HtmlCombinedWidgetTest.java @@ -21,44 +21,42 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class HtmlCombinedWidgetTest implements WidgetTest{ +public class HtmlCombinedWidgetTest implements WidgetTest { private static ChromeDriver driver; private static RottenTomatoesAppWithCombinedWidgets rottenTomatoes; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { if (Platform.getCurrent().is(Platform.WINDOWS)) { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); - } - else { + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); + } else { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); } driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); rottenTomatoes = new RottenTomatoesAppWithCombinedWidgets(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoes); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoes); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) - driver.get("file:///" + new File("src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html").getAbsolutePath()); + driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { + @Before public void setUp() throws Exception { if (driver != null) - driver.quit(); + driver.get("file:///" + new File( + "src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html") + .getAbsolutePath()); } - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -69,9 +67,7 @@ public void checkACommonWidget() { rottenTomatoes.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -83,9 +79,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -96,13 +90,10 @@ public void checkAnExtendedWidget() { rottenTomatoes.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -111,8 +102,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/RottenTomatoesAppWithCombinedWidgets.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/RottenTomatoesAppWithCombinedWidgets.java index 4bb38651f..cc1d880ae 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/RottenTomatoesAppWithCombinedWidgets.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/RottenTomatoesAppWithCombinedWidgets.java @@ -22,15 +22,13 @@ public class RottenTomatoesAppWithCombinedWidgets { @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") - @SelendroidFindBy(id = "lvMovies") - @FindBy(id = "movies-collection") - private CombinedMovies simpleMovies; + @SelendroidFindBy(id = "lvMovies") @FindBy(id = "movies-collection") private CombinedMovies + simpleMovies; @AndroidFindBys({@AndroidFindBy(id = "android:id/content"), - @AndroidFindBy(className = "android.widget.RelativeLayout")}) - @FindBy(id = "main_container") - @SelendroidFindBy(className = "android.widget.RelativeLayout") - private CombinedReview simpleReview; + @AndroidFindBy(className = "android.widget.RelativeLayout")}) @FindBy(id = "main_container") + @SelendroidFindBy(className = "android.widget.RelativeLayout") private CombinedReview + simpleReview; private AnnotatedCombinedMovies annotatedCombinedMovies; @@ -40,24 +38,20 @@ public class RottenTomatoesAppWithCombinedWidgets { private ExtendedCombinedReview extendedCombinedReview; - @AndroidFindBy(id = "fakeId") - @FindBy(id = "fakeId") - private ExtendedCombinedMovies fakeMovies; + @AndroidFindBy(id = "fakeId") @FindBy(id = "fakeId") private ExtendedCombinedMovies fakeMovies; - @AndroidFindBy(id = "fakeId") - @FindBy(id = "fakeId") - private ExtendedCombinedReview fakeReview; + @AndroidFindBy(id = "fakeId") @FindBy(id = "fakeId") private ExtendedCombinedReview fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -65,15 +59,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedCombinedMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedCombinedMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedCombinedReview.title())); assertTrue(!StringUtils.isBlank(annotatedCombinedReview.score())); assertTrue(!StringUtils.isBlank(annotatedCombinedReview.info())); @@ -81,15 +75,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedCombinedMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedCombinedMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedCombinedReview.title())); assertTrue(!StringUtils.isBlank(extendedCombinedReview.score())); assertTrue(!StringUtils.isBlank(extendedCombinedReview.info())); @@ -98,11 +92,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/SelendroidCombinedWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/SelendroidCombinedWidgetTest.java index 0388341aa..de398f15f 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/SelendroidCombinedWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/SelendroidCombinedWidgetTest.java @@ -9,7 +9,6 @@ import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; -import io.appium.java_client.service.local.flags.GeneralServerFlag; import org.apache.commons.lang3.StringUtils; import org.junit.*; import org.openqa.selenium.NoSuchElementException; @@ -22,23 +21,25 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class SelendroidCombinedWidgetTest implements WidgetTest{ +public class SelendroidCombinedWidgetTest implements WidgetTest { private static int SELENDROID_PORT = 9999; - - private AndroidDriver driver; private static AppiumDriverLocalService service; + private AndroidDriver driver; private RottenTomatoesAppWithCombinedWidgets rottenTomatoes; private TimeOutDuration duration; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { AppiumServiceBuilder builder = new AppiumServiceBuilder(); service = builder.build(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "android-rottentomatoes-demo-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); @@ -52,20 +53,11 @@ public void setUp() throws Exception { PageFactory.initElements(new AppiumFieldDecorator(driver, duration), rottenTomatoes); } - @After - public void tearDown() throws Exception { + @After public void tearDown() throws Exception { driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { - if (service != null) - service.stop(); - } - - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoes.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -76,9 +68,7 @@ public void checkACommonWidget() { rottenTomatoes.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoes.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -90,9 +80,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoes.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -103,14 +91,11 @@ public void checkAnExtendedWidget() { rottenTomatoes.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { duration.setTime(5); try { assertTrue(rottenTomatoes.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -119,8 +104,7 @@ public void checkTheLocatorOverridingOnAWidget() { driver.getPageSource(); //forcing the refreshing hierarchy try { rottenTomatoes.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovie.java index 7f379b667..a40e0e3fb 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovie.java @@ -5,8 +5,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -@AndroidFindBy(className = "android.widget.RelativeLayout") -@FindBy(className = "mb-movie") +@AndroidFindBy(className = "android.widget.RelativeLayout") @FindBy(className = "mb-movie") public class AnnotatedCombinedMovie extends CombinedMovie { protected AnnotatedCombinedMovie(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovies.java index 55cc5a9cf..67c5c922e 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedMovies.java @@ -11,9 +11,8 @@ import java.util.List; @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/lvMovies") -@SelendroidFindBy(id = "lvMovies") -@FindBy(id = "movies-collection") -public class AnnotatedCombinedMovies extends Movies{ +@SelendroidFindBy(id = "lvMovies") @FindBy(id = "movies-collection") +public class AnnotatedCombinedMovies extends Movies { List movieList; @@ -26,13 +25,11 @@ protected AnnotatedCombinedMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedReview.java index 201097d2e..948ef2c19 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/annotated/AnnotatedCombinedReview.java @@ -9,10 +9,9 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -@FindBy(id = "main_container") -@SelendroidFindBy(className = "android.widget.RelativeLayout") +@FindBy(id = "main_container") @SelendroidFindBy(className = "android.widget.RelativeLayout") @AndroidFindBys({@AndroidFindBy(id = "android:id/content"), - @AndroidFindBy(className = "android.widget.RelativeLayout")}) + @AndroidFindBy(className = "android.widget.RelativeLayout")}) public class AnnotatedCombinedReview extends CombinedReview { protected AnnotatedCombinedReview(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/extended/ExtendedCombinedReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/extended/ExtendedCombinedReview.java index ad109b5e1..853b83f93 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/extended/ExtendedCombinedReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/extended/ExtendedCombinedReview.java @@ -3,7 +3,7 @@ import io.appium.java_client.pagefactory_tests.widgets.combined.annotated.AnnotatedCombinedReview; import org.openqa.selenium.WebElement; -public class ExtendedCombinedReview extends AnnotatedCombinedReview{ +public class ExtendedCombinedReview extends AnnotatedCombinedReview { protected ExtendedCombinedReview(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovie.java index 78ae85006..702b61491 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovie.java @@ -7,49 +7,39 @@ import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.FindBy; -public class CombinedMovie extends Movie{ +public class CombinedMovie extends Movie { @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") - @SelendroidFindBy(id = "tvTitle") - @FindBy(className = "movieTitle") - private RemoteWebElement title; + @SelendroidFindBy(id = "tvTitle") @FindBy(className = "movieTitle") private RemoteWebElement + title; @AndroidFindBy(uiAutomator = "resourceId(\"com.codepath.example.rottentomatoes:id/tvCriticsScore\")") - @FindBy(className = "tMeterScore") - @SelendroidFindBy(id = "tvCriticsScore") + @FindBy(className = "tMeterScore") @SelendroidFindBy(id = "tvCriticsScore") private RemoteWebElement score; - @AndroidFindBy(accessibility = "poster image") - @SelendroidFindBy(id = "ivPosterImage") - @FindBy(className = "poster_container") - private RemoteWebElement poster; + @AndroidFindBy(accessibility = "poster image") @SelendroidFindBy(id = "ivPosterImage") + @FindBy(className = "poster_container") private RemoteWebElement poster; - @AndroidFindBy(accessibility = "poster image") - @SelendroidFindBy(id = "ivPosterImage") - @FindBy(xpath = ".//*[@class=\"movie_info\"]/a/h3") - private RemoteWebElement movieSwitcher; + @AndroidFindBy(accessibility = "poster image") @SelendroidFindBy(id = "ivPosterImage") + @FindBy(xpath = ".//*[@class=\"movie_info\"]/a/h3") private RemoteWebElement movieSwitcher; protected CombinedMovie(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } - @Override - public void goToReview() { + @Override public void goToReview() { movieSwitcher.click(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovies.java index 274a766cb..1acc2fe3a 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedMovies.java @@ -9,10 +9,9 @@ import java.util.List; -public class CombinedMovies extends Movies{ +public class CombinedMovies extends Movies { - @AndroidFindBy(className = "android.widget.RelativeLayout") - @FindBy(className = "mb-movie") + @AndroidFindBy(className = "android.widget.RelativeLayout") @FindBy(className = "mb-movie") List movieList; /* @@ -24,13 +23,11 @@ protected CombinedMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedReview.java index d4d463699..aefc13a3c 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/simple/CombinedReview.java @@ -8,12 +8,10 @@ import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.FindBy; -public class CombinedReview extends Review{ +public class CombinedReview extends Review { @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvTitle") - @FindBy(id = "movie-title") - @SelendroidFindBy(id = "tvTitle") - private RemoteWebElement title; + @FindBy(id = "movie-title") @SelendroidFindBy(id = "tvTitle") private RemoteWebElement title; @AndroidFindBy(uiAutomator = "resourceId(\"com.codepath.example.rottentomatoes:id/tvCriticsScore\")") @SelendroidFindBy(id = "tvCriticsScore") @@ -21,36 +19,30 @@ public class CombinedReview extends Review{ private RemoteWebElement score; @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/tvSynopsis") - @SelendroidFindBy(id = "tvSynopsis") - private RemoteWebElement movieSynopsis; + @SelendroidFindBy(id = "tvSynopsis") private RemoteWebElement movieSynopsis; @AndroidFindBy(id = "com.codepath.example.rottentomatoes:id/ivPosterImage") - @SelendroidFindBy(id = "ivPosterImage") - @FindBy(className = "videoPic") - private RemoteWebElement poster; + @SelendroidFindBy(id = "ivPosterImage") @FindBy(className = "videoPic") private RemoteWebElement + poster; protected CombinedReview(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public String info() { + @Override public String info() { return movieSynopsis.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/HtmlWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/HtmlWidgetTest.java index 8923e0452..233c6bad8 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/HtmlWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/HtmlWidgetTest.java @@ -21,44 +21,42 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class HtmlWidgetTest implements WidgetTest{ +public class HtmlWidgetTest implements WidgetTest { private static ChromeDriver driver; private static RottenTomatoesSite rottenTomatoesSite; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { if (Platform.getCurrent().is(Platform.WINDOWS)) { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); - } - else { + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver.exe"); + } else { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, - "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); + "src/test/java/io/appium/java_client/pagefactory_tests/chromedriver"); } driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); rottenTomatoesSite = new RottenTomatoesSite(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoesSite); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoesSite); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { if (driver != null) - driver.get("file:///" + new File("src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html").getAbsolutePath()); + driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { + @Before public void setUp() throws Exception { if (driver != null) - driver.quit(); + driver.get("file:///" + new File( + "src/test/java/io/appium/java_client/RottenTomatoesSnapshot.html") + .getAbsolutePath()); } - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoesSite.getSimpleMovieCount() == 30); Movie movie = rottenTomatoesSite.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -69,9 +67,7 @@ public void checkACommonWidget() { rottenTomatoesSite.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoesSite.getAnnotatedMovieCount() == 30); Movie movie = rottenTomatoesSite.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -83,9 +79,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoesSite.getExtendeddMovieCount() == 30); Movie movie = rottenTomatoesSite.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -96,13 +90,10 @@ public void checkAnExtendedWidget() { rottenTomatoesSite.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoesSite.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -111,8 +102,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoesSite.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/RottenTomatoesSite.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/RottenTomatoesSite.java index 8a15af354..b5fecbe59 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/RottenTomatoesSite.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/RottenTomatoesSite.java @@ -18,11 +18,9 @@ */ public class RottenTomatoesSite { - @FindBy(id = "movies-collection") - private HtmlMovies simpleMovies; + @FindBy(id = "movies-collection") private HtmlMovies simpleMovies; - @FindBy(id = "main_container") - private HtmlReview simpleReview; + @FindBy(id = "main_container") private HtmlReview simpleReview; private AnnotatedHtmlMovies annotatedHtmlMovies; @@ -32,22 +30,20 @@ public class RottenTomatoesSite { private ExtendedHtmlReview extendedHtmlReview; - @FindBy(id = "fakeId") - private ExtendedHtmlMovies fakeMovies; + @FindBy(id = "fakeId") private ExtendedHtmlMovies fakeMovies; - @FindBy(id = "fakeId") - private ExtendedHtmlReview fakeReview; + @FindBy(id = "fakeId") private ExtendedHtmlReview fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -55,15 +51,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedHtmlMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedHtmlMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedHtmlReview.title())); assertTrue(!StringUtils.isBlank(annotatedHtmlReview.score())); assertTrue(!StringUtils.isBlank(annotatedHtmlReview.info())); @@ -71,15 +67,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedHtmlMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedHtmlMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedHtmlReview.title())); assertTrue(!StringUtils.isBlank(extendedHtmlReview.score())); assertTrue(!StringUtils.isBlank(extendedHtmlReview.info())); @@ -88,11 +84,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovie.java index 9796ff1dc..80a703d54 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovie.java @@ -4,8 +4,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -@FindBy(className = "mb-movie") -public class AnnotatedHtmlMovie extends HtmlMovie { +@FindBy(className = "mb-movie") public class AnnotatedHtmlMovie extends HtmlMovie { protected AnnotatedHtmlMovie(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovies.java index 898031704..e4462d056 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlMovies.java @@ -7,8 +7,7 @@ import java.util.List; -@FindBy(id = "movies-collection") -public class AnnotatedHtmlMovies extends Movies{ +@FindBy(id = "movies-collection") public class AnnotatedHtmlMovies extends Movies { List movieList; /* @@ -20,13 +19,11 @@ protected AnnotatedHtmlMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlReview.java index bf9e49b2a..26c7071f2 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/annotated/AnnotatedHtmlReview.java @@ -5,8 +5,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -@FindBy(id = "main_container") -public class AnnotatedHtmlReview extends HtmlReview { +@FindBy(id = "main_container") public class AnnotatedHtmlReview extends HtmlReview { protected AnnotatedHtmlReview(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovie.java index ec0991e14..1f83f56d9 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovie.java @@ -4,19 +4,15 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -public class HtmlMovie extends Movie{ +public class HtmlMovie extends Movie { - @FindBy(className = "movieTitle") - private WebElement title; + @FindBy(className = "movieTitle") private WebElement title; - @FindBy(className = "tMeterScore") - private WebElement score; + @FindBy(className = "tMeterScore") private WebElement score; - @FindBy(className = "poster_container") - private WebElement poster; + @FindBy(className = "poster_container") private WebElement poster; - @FindBy(xpath = ".//*[@class=\"movie_info\"]/a/h3") - private WebElement linkToMovie; + @FindBy(xpath = ".//*[@class=\"movie_info\"]/a/h3") private WebElement linkToMovie; @@ -24,23 +20,19 @@ protected HtmlMovie(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } - @Override - public void goToReview() { + @Override public void goToReview() { linkToMovie.click(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovies.java index e5dd55327..d4e115853 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlMovies.java @@ -7,10 +7,9 @@ import java.util.List; -public class HtmlMovies extends Movies{ +public class HtmlMovies extends Movies { - @FindBy(className = "mb-movie") - List movieList; + @FindBy(className = "mb-movie") List movieList; /* There could be additional behavior. @@ -21,13 +20,11 @@ protected HtmlMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlReview.java index 10dc67293..1e93c5140 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/html/simple/HtmlReview.java @@ -5,41 +5,35 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; -public class HtmlReview extends Review{ +public class HtmlReview extends Review { - @FindBy(id = "movie-title") - private WebElement title; + @FindBy(id = "movie-title") private WebElement title; @FindBy(xpath = ".//*[@id=\"tomato_meter_link\"]//*[@itemprop=\"ratingValue\"]") private WebElement score; private WebElement movieSynopsis; - @FindBy(className = "videoPic") - private WebElement poster; + @FindBy(className = "videoPic") private WebElement poster; protected HtmlReview(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public String info() { + @Override public String info() { return movieSynopsis.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/IOSWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/IOSWidgetTest.java index 85fe020b4..48282fc2a 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/IOSWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/IOSWidgetTest.java @@ -19,20 +19,23 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class IOSWidgetTest implements WidgetTest{ +public class IOSWidgetTest implements WidgetTest { - private IOSDriver driver; private static AppiumDriverLocalService service; + private IOSDriver driver; private RottenTomatoesIOSApp rottenTomatoesApp; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "RottenTomatoes.zip"); @@ -44,24 +47,17 @@ public void setUp() throws Exception { driver = new IOSDriver<>(service.getUrl(), capabilities); rottenTomatoesApp = new RottenTomatoesIOSApp(); - PageFactory.initElements(new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), rottenTomatoesApp); + PageFactory.initElements( + new AppiumFieldDecorator(driver, new TimeOutDuration(5, TimeUnit.SECONDS)), + rottenTomatoesApp); } - @After - public void tearDown() { + @After public void tearDown() { if (driver != null) driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { - if (service != null) - service.stop(); - } - - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoesApp.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoesApp.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -72,9 +68,7 @@ public void checkACommonWidget() { rottenTomatoesApp.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoesApp.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -86,9 +80,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoesApp.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -99,13 +91,10 @@ public void checkAnExtendedWidget() { rottenTomatoesApp.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { try { assertTrue(rottenTomatoesApp.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -114,8 +103,7 @@ public void checkTheLocatorOverridingOnAWidget() { try { rottenTomatoesApp.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/RottenTomatoesIOSApp.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/RottenTomatoesIOSApp.java index 91f7d387a..5a943daf9 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/RottenTomatoesIOSApp.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/RottenTomatoesIOSApp.java @@ -19,11 +19,9 @@ */ public class RottenTomatoesIOSApp { - @iOSFindBy(className = "UIATableView") - private IOSMovies simpleMovies; + @iOSFindBy(className = "UIATableView") private IOSMovies simpleMovies; - @iOSFindBy(xpath = ".//UIAWindow[2]") - private IOSReview simpleReview; + @iOSFindBy(xpath = ".//UIAWindow[2]") private IOSReview simpleReview; private AnnotatedIOSMovies annotatedIOSMovies; @@ -33,22 +31,20 @@ public class RottenTomatoesIOSApp { private ExtendedIOSReview extendedIOSReview; - @iOSFindBy(id = "fakeId") - private ExtendedIOSMovies fakeMovies; + @iOSFindBy(id = "fakeId") private ExtendedIOSMovies fakeMovies; - @iOSFindBy(id = "fakeId") - private ExtendedIOSReview fakeReview; + @iOSFindBy(id = "fakeId") private ExtendedIOSReview fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -56,15 +52,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedIOSMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedIOSMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedIOSReview.title())); assertTrue(!StringUtils.isBlank(annotatedIOSReview.score())); assertTrue(!StringUtils.isBlank(annotatedIOSReview.info())); @@ -72,15 +68,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedIOSMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedIOSMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedIOSReview.title())); assertTrue(!StringUtils.isBlank(extendedIOSReview.score())); assertTrue(!StringUtils.isBlank(extendedIOSReview.info())); @@ -89,11 +85,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovie.java index 979c91656..dd3fe027f 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovie.java @@ -4,8 +4,7 @@ import io.appium.java_client.pagefactory_tests.widgets.ios.simple.IOSMovie; import org.openqa.selenium.WebElement; -@iOSFindBy(className = "UIATableCell") -public class AnnotatedIOSMovie extends IOSMovie { +@iOSFindBy(className = "UIATableCell") public class AnnotatedIOSMovie extends IOSMovie { protected AnnotatedIOSMovie(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovies.java index c1680a13e..29fd05782 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSMovies.java @@ -7,8 +7,7 @@ import java.util.List; -@iOSFindBy(className = "UIATableView") -public class AnnotatedIOSMovies extends Movies{ +@iOSFindBy(className = "UIATableView") public class AnnotatedIOSMovies extends Movies { List movieList; @@ -21,13 +20,11 @@ protected AnnotatedIOSMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSReview.java index 396b400cb..407c742b1 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/annotated/AnnotatedIOSReview.java @@ -4,8 +4,7 @@ import io.appium.java_client.pagefactory_tests.widgets.ios.simple.IOSReview; import org.openqa.selenium.WebElement; -@iOSFindBy(xpath = ".//UIAWindow[2]") -public class AnnotatedIOSReview extends IOSReview { +@iOSFindBy(xpath = ".//UIAWindow[2]") public class AnnotatedIOSReview extends IOSReview { protected AnnotatedIOSReview(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/extended/ExtendedIOSMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/extended/ExtendedIOSMovies.java index 55b23248c..5dfab6e49 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/extended/ExtendedIOSMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/extended/ExtendedIOSMovies.java @@ -1,9 +1,9 @@ package io.appium.java_client.pagefactory_tests.widgets.ios.extended; -import org.openqa.selenium.WebElement; import io.appium.java_client.pagefactory_tests.widgets.ios.annotated.AnnotatedIOSMovies; +import org.openqa.selenium.WebElement; -public class ExtendedIOSMovies extends AnnotatedIOSMovies{ +public class ExtendedIOSMovies extends AnnotatedIOSMovies { protected ExtendedIOSMovies(WebElement element) { super(element); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovie.java index cb92c847d..5cac8c33a 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovie.java @@ -4,35 +4,31 @@ import io.appium.java_client.pagefactory.iOSFindBy; import io.appium.java_client.pagefactory_tests.widgets.Movie; import org.openqa.selenium.WebElement; -import java.util.List; import org.openqa.selenium.remote.RemoteWebElement; -public class IOSMovie extends Movie{ +import java.util.List; + +public class IOSMovie extends Movie { - @iOSFindBy(className = "UIAStaticText") - private List staticTexts; + @iOSFindBy(className = "UIAStaticText") private List staticTexts; protected IOSMovie(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return staticTexts.get(0).getText(); } - @Override - public String score() { + @Override public String score() { return staticTexts.get(3).getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return ((RemoteWebElement) getWrappedElement()).getSize(); } - @Override - public void goToReview() { + @Override public void goToReview() { ((IOSElement) getWrappedElement()).tap(1, 1500); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovies.java index 22a729b33..7deb9575d 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSMovies.java @@ -8,10 +8,9 @@ import java.util.List; //classNme = UIATableView -public class IOSMovies extends Movies{ +public class IOSMovies extends Movies { - @iOSFindBy(className = "UIATableCell") - List movieList; + @iOSFindBy(className = "UIATableCell") List movieList; /* There could be additional behavior. @@ -22,13 +21,11 @@ protected IOSMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSReview.java index 947ab2df5..fd18e09c6 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/ios/simple/IOSReview.java @@ -7,41 +7,34 @@ import org.openqa.selenium.WebElement; //className = UIAWindow -public class IOSReview extends Review{ +public class IOSReview extends Review { @iOSFindBys({@iOSFindBy(className = "UIANavigationBar"), - @iOSFindBy(className = "UIAStaticText")}) - private IOSElement title; + @iOSFindBy(className = "UIAStaticText")}) private IOSElement title; - @iOSFindBys({@iOSFindBy(className = "UIAScrollView"), - @iOSFindBy(className = "UIAStaticText")}) + @iOSFindBys({@iOSFindBy(className = "UIAScrollView"), @iOSFindBy(className = "UIAStaticText")}) private IOSElement synopsis; - @iOSFindBy(className = "UIAImage") - private IOSElement poster; + @iOSFindBy(className = "UIAImage") private IOSElement poster; protected IOSReview(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return "100"; } - @Override - public String info() { + @Override public String info() { return synopsis.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/RottenTomatoesSelendroidApp.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/RottenTomatoesSelendroidApp.java index 4fb5209a1..57e7596cd 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/RottenTomatoesSelendroidApp.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/RottenTomatoesSelendroidApp.java @@ -18,11 +18,10 @@ */ public class RottenTomatoesSelendroidApp { - @SelendroidFindBy(id = "lvMovies") - private SelendroidMovies simpleMovies; + @SelendroidFindBy(id = "lvMovies") private SelendroidMovies simpleMovies; - @SelendroidFindBy(className = "android.widget.RelativeLayout") - private SelendroidReview simpleReview; + @SelendroidFindBy(className = "android.widget.RelativeLayout") private SelendroidReview + simpleReview; private AnnotatedSelendroidMovies annotatedSelendroidMovies; @@ -32,22 +31,20 @@ public class RottenTomatoesSelendroidApp { private ExtendedSelendroidReview extendedSelendroidReview; - @SelendroidFindBy(id = "fakeId") - private ExtendedSelendroidMovies fakeMovies; + @SelendroidFindBy(id = "fakeId") private ExtendedSelendroidMovies fakeMovies; - @SelendroidFindBy(id = "fakeId") - private ExtendedSelendroidReview fakeReview; + @SelendroidFindBy(id = "fakeId") private ExtendedSelendroidReview fakeReview; - public int getSimpleMovieCount(){ + public int getSimpleMovieCount() { return simpleMovies.getMovieCount(); } - public Movie getASimpleMovie(int index){ + public Movie getASimpleMovie(int index) { return simpleMovies.getMovie(index); } - public void checkSimpleReview(){ + public void checkSimpleReview() { assertTrue(!StringUtils.isBlank(simpleReview.title())); assertTrue(!StringUtils.isBlank(simpleReview.score())); assertTrue(!StringUtils.isBlank(simpleReview.info())); @@ -55,15 +52,15 @@ public void checkSimpleReview(){ } ///////////////////////////////////////////////////////// - public int getAnnotatedMovieCount(){ + public int getAnnotatedMovieCount() { return annotatedSelendroidMovies.getMovieCount(); } - public Movie getAnAnnotatedMovie(int index){ + public Movie getAnAnnotatedMovie(int index) { return annotatedSelendroidMovies.getMovie(index); } - public void checkAnnotatedReview(){ + public void checkAnnotatedReview() { assertTrue(!StringUtils.isBlank(annotatedSelendroidReview.title())); assertTrue(!StringUtils.isBlank(annotatedSelendroidReview.score())); assertTrue(!StringUtils.isBlank(annotatedSelendroidReview.info())); @@ -71,15 +68,15 @@ public void checkAnnotatedReview(){ } ///////////////////////////////////////////////////////// - public int getExtendeddMovieCount(){ + public int getExtendeddMovieCount() { return extendedSelendroidMovies.getMovieCount(); } - public Movie getAnExtendedMovie(int index){ + public Movie getAnExtendedMovie(int index) { return extendedSelendroidMovies.getMovie(index); } - public void checkExtendedReview(){ + public void checkExtendedReview() { assertTrue(!StringUtils.isBlank(extendedSelendroidReview.title())); assertTrue(!StringUtils.isBlank(extendedSelendroidReview.score())); assertTrue(!StringUtils.isBlank(extendedSelendroidReview.info())); @@ -88,11 +85,11 @@ public void checkExtendedReview(){ ///////////////////////////////////////////////////////// - public int getFakedMovieCount(){ + public int getFakedMovieCount() { return fakeMovies.getMovieCount(); } - public void checkFakeReview(){ + public void checkFakeReview() { assertTrue(!StringUtils.isBlank(fakeReview.title())); assertTrue(!StringUtils.isBlank(fakeReview.score())); assertTrue(!StringUtils.isBlank(fakeReview.info())); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/SelendroidWidgetTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/SelendroidWidgetTest.java index 38fb1b1ac..e482a5f7d 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/SelendroidWidgetTest.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/SelendroidWidgetTest.java @@ -10,7 +10,6 @@ import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; -import io.appium.java_client.service.local.flags.GeneralServerFlag; import org.apache.commons.lang3.StringUtils; import org.junit.*; import org.openqa.selenium.NoSuchElementException; @@ -23,23 +22,25 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class SelendroidWidgetTest implements WidgetTest{ +public class SelendroidWidgetTest implements WidgetTest { private static int SELENDROID_PORT = 9999; - - private AndroidDriver driver; private static AppiumDriverLocalService service; - private RottenTomatoesSelendroidApp rottenTomatoesApp; TimeOutDuration duration; + private AndroidDriver driver; + private RottenTomatoesSelendroidApp rottenTomatoesApp; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeClass public static void beforeClass() throws Exception { AppiumServiceBuilder builder = new AppiumServiceBuilder(); service = builder.build(); service.start(); } - @Before - public void setUp() throws Exception { + @AfterClass public static void afterClass() throws Exception { + if (service != null) + service.stop(); + } + + @Before public void setUp() throws Exception { File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "android-rottentomatoes-demo-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); @@ -55,20 +56,11 @@ public void setUp() throws Exception { PageFactory.initElements(new AppiumFieldDecorator(driver, duration), rottenTomatoesApp); } - @After - public void tearDown() throws Exception { + @After public void tearDown() throws Exception { driver.quit(); } - @AfterClass - public static void afterClass() throws Exception { - if (service != null) - service.stop(); - } - - @Test - @Override - public void checkACommonWidget() { + @Test @Override public void checkACommonWidget() { assertTrue(rottenTomatoesApp.getSimpleMovieCount() >= 1); Movie movie = rottenTomatoesApp.getASimpleMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -79,9 +71,7 @@ public void checkACommonWidget() { rottenTomatoesApp.checkSimpleReview(); } - @Override - @Test - public void checkAnAnnotatedWidget() { + @Override @Test public void checkAnAnnotatedWidget() { assertTrue(rottenTomatoesApp.getAnnotatedMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnAnnotatedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -93,9 +83,7 @@ public void checkAnAnnotatedWidget() { } - @Override - @Test - public void checkAnExtendedWidget() { + @Override @Test public void checkAnExtendedWidget() { assertTrue(rottenTomatoesApp.getExtendeddMovieCount() >= 1); Movie movie = rottenTomatoesApp.getAnExtendedMovie(0); assertTrue(!StringUtils.isBlank(movie.title())); @@ -106,14 +94,11 @@ public void checkAnExtendedWidget() { rottenTomatoesApp.checkExtendedReview(); } - @Override - @Test - public void checkTheLocatorOverridingOnAWidget() { + @Override @Test public void checkTheLocatorOverridingOnAWidget() { duration.setTime(5); try { assertTrue(rottenTomatoesApp.getFakedMovieCount() == 0); - } - catch (Exception e){ + } catch (Exception e) { if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) throw e; } @@ -122,8 +107,7 @@ public void checkTheLocatorOverridingOnAWidget() { driver.getPageSource(); //forcing the refreshing hierarchy try { rottenTomatoesApp.checkFakeReview(); - } - catch (Exception e){ + } catch (Exception e) { if (NoSuchElementException.class.isAssignableFrom(e.getClass())) return; else diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovie.java index 9177c2453..7e555eb21 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovie.java @@ -4,8 +4,8 @@ import io.appium.java_client.pagefactory_tests.widgets.selendroid.simple.SelendroidMovie; import org.openqa.selenium.WebElement; -@SelendroidFindBy(className = "android.widget.RelativeLayout") -public class AnnotatedSelendroidMovie extends SelendroidMovie{ +@SelendroidFindBy(className = "android.widget.RelativeLayout") public class AnnotatedSelendroidMovie + extends SelendroidMovie { protected AnnotatedSelendroidMovie(WebElement element) { super(element); diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovies.java index 068a190d0..1d4cd51b0 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidMovies.java @@ -8,8 +8,7 @@ import java.util.List; -@SelendroidFindBy(id = "lvMovies") -public class AnnotatedSelendroidMovies extends Movies{ +@SelendroidFindBy(id = "lvMovies") public class AnnotatedSelendroidMovies extends Movies { List movieList; @@ -22,13 +21,11 @@ protected AnnotatedSelendroidMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidReview.java index ccc76aca1..e1c5afac3 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/annotated/AnnotatedSelendroidReview.java @@ -2,7 +2,6 @@ import io.appium.java_client.pagefactory.SelendroidFindBy; -import io.appium.java_client.pagefactory.SelendroidFindBys; import io.appium.java_client.pagefactory_tests.widgets.selendroid.simple.SelendroidReview; import org.openqa.selenium.WebElement; diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovie.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovie.java index bb0dec1ce..75dfa7754 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovie.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovie.java @@ -5,38 +5,31 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; -public class SelendroidMovie extends Movie{ +public class SelendroidMovie extends Movie { - @SelendroidFindBy(id = "tvTitle") - private RemoteWebElement title; + @SelendroidFindBy(id = "tvTitle") private RemoteWebElement title; - @SelendroidFindBy(id = "tvCriticsScore") - private RemoteWebElement score; + @SelendroidFindBy(id = "tvCriticsScore") private RemoteWebElement score; - @SelendroidFindBy(id = "ivPosterImage") - private RemoteWebElement poster; + @SelendroidFindBy(id = "ivPosterImage") private RemoteWebElement poster; protected SelendroidMovie(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } - @Override - public void goToReview() { + @Override public void goToReview() { getWrappedElement().click(); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovies.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovies.java index 04b8875ba..375c30ee4 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovies.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidMovies.java @@ -8,10 +8,9 @@ import java.util.List; -public class SelendroidMovies extends Movies{ +public class SelendroidMovies extends Movies { - @SelendroidFindBy(className = "android.widget.RelativeLayout") - List movieList; + @SelendroidFindBy(className = "android.widget.RelativeLayout") List movieList; /* There could be additional behavior. @@ -22,13 +21,11 @@ protected SelendroidMovies(WebElement element) { super(element); } - @Override - public int getMovieCount() { + @Override public int getMovieCount() { return movieList.size(); } - @Override - public Movie getMovie(int index) { + @Override public Movie getMovie(int index) { return movieList.get(index); } } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidReview.java b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidReview.java index 0ac389d45..1e6532c48 100644 --- a/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidReview.java +++ b/src/test/java/io/appium/java_client/pagefactory_tests/widgets/selendroid/simple/SelendroidReview.java @@ -6,42 +6,34 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; -public class SelendroidReview extends Review{ +public class SelendroidReview extends Review { - @SelendroidFindBy(id = "tvTitle") - private RemoteWebElement title; + @SelendroidFindBy(id = "tvTitle") private RemoteWebElement title; - @SelendroidFindBy(id = "tvCriticsScore") - private RemoteWebElement score; + @SelendroidFindBy(id = "tvCriticsScore") private RemoteWebElement score; - @SelendroidFindBy(id = "tvSynopsis") - private RemoteWebElement synopsis; + @SelendroidFindBy(id = "tvSynopsis") private RemoteWebElement synopsis; - @SelendroidFindBy(id = "ivPosterImage") - private RemoteWebElement poster; + @SelendroidFindBy(id = "ivPosterImage") private RemoteWebElement poster; protected SelendroidReview(WebElement element) { super(element); } - @Override - public String title() { + @Override public String title() { return title.getText(); } - @Override - public String score() { + @Override public String score() { return score.getText(); } - @Override - public String info() { + @Override public String info() { return synopsis.getText(); } - @Override - public Object getPoster() { + @Override public Object getPoster() { return poster.getSize(); } }