Example usage for org.openqa.selenium.remote BrowserType ANDROID

List of usage examples for org.openqa.selenium.remote BrowserType ANDROID

Introduction

In this page you can find the example usage for org.openqa.selenium.remote BrowserType ANDROID.

Prototype

String ANDROID

To view the source code for org.openqa.selenium.remote BrowserType ANDROID.

Click Source Link

Usage

From source file:io.selendroid.common.SelendroidCapabilities.java

License:Apache License

public static DesiredCapabilities android(DeviceTargetPlatform platform) {
    SelendroidCapabilities capabilities = new SelendroidCapabilities();
    capabilities.setCapability(BROWSER_NAME, BrowserType.ANDROID);
    capabilities.setCapability(VERSION, "");
    capabilities.setCapability(PLATFORM, "android");
    capabilities.setCapability(PLATFORM_NAME, "android");
    capabilities.setCapability(PLATFORM_VERSION, platform.getApi());
    return capabilities;
}

From source file:io.selendroid.server.model.SelendroidStandaloneDriver.java

License:Apache License

void initApplicationsUnderTest(SelendroidConfiguration serverConfiguration)
        throws AndroidSdkException {
    if (serverConfiguration == null) {
        throw new SelendroidException("Configuration error - serverConfiguration can't be null.");
    }//w w  w  .  j av a2  s . c om
    this.serverConfiguration = serverConfiguration;

    // each of the apps specified on the command line need to get resigned
    // and 'stored' to be installed on the device
    for (String appPath : serverConfiguration.getSupportedApps()) {
        File file = new File(appPath);
        if (file.exists()) {

            AndroidApp app = null;
            try {
                app = selendroidApkBuilder.resignApp(file);
            } catch (ShellCommandException e1) {
                throw new SessionNotCreatedException(
                        "An error occurred while resigning the app '" + file.getName() + "'. ", e1);
            }
            String appId = null;
            try {
                appId = app.getAppId();
            } catch (SelendroidException e) {
                log.info("Ignoring app because an error occurred reading the app details: "
                        + file.getAbsolutePath());
                log.info(e.getMessage());
            }
            if (appId != null && !appsStore.containsKey(appId)) {
                appsStore.put(appId, app);
                log.info("App " + appId + " has been added to selendroid standalone server.");
            }
        } else {
            log.severe("Ignoring app because it was not found: " + file.getAbsolutePath());
        }
    }

    if (!serverConfiguration.isNoWebViewApp()) {
        // extract the 'AndroidDriver' app and show it as available
        try {
            // using "android" as the app name, because that is the desired capability default in
            // selenium for
            // DesiredCapabilities.ANDROID
            AndroidApp app = selendroidApkBuilder.resignApp(androidDriverAPKBuilder.extractAndroidDriverAPK());
            appsStore.put(BrowserType.ANDROID, app);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else if (appsStore.isEmpty()) {
        // note this only happens now when someone uses -noWebViewApp & forgets to specify -aut/app
        // (or the app doesn't exist or some other error condition above ^ )
        throw new SelendroidException(
                "Fatal error initializing SelendroidDriver: configured app(s) have not been found.");
    }

}

From source file:io.selendroid.server.model.SelendroidStandaloneDriver.java

License:Apache License

public String createNewTestSession(JSONObject caps, Integer retries) throws AndroidSdkException, JSONException {
    SelendroidCapabilities desiredCapabilities = null;

    // Convert the JSON capabilities to SelendroidCapabilities
    try {/*from   w  w  w.j  a  va 2 s.  c o m*/
        desiredCapabilities = new SelendroidCapabilities(caps);
    } catch (JSONException e) {
        throw new SelendroidException("Desired capabilities cannot be parsed.");
    }

    // Find the App being requested for use
    AndroidApp app = appsStore.get(desiredCapabilities.getAut());
    if (app == null) {
        throw new SessionNotCreatedException(
                "The requested application under test is not configured in selendroid server.");
    }
    // adjust app based on capabilities (some parameters are session specific)
    app = augmentApp(app, desiredCapabilities);

    // Find a device to match the capabilities
    AndroidDevice device = null;
    try {
        device = getAndroidDevice(desiredCapabilities);
    } catch (AndroidDeviceException e) {
        SessionNotCreatedException error = new SessionNotCreatedException(
                "Error occured while finding android device: " + e.getMessage());
        e.printStackTrace();
        log.severe(error.getMessage());
        throw error;
    }

    // If we are using an emulator need to start it up
    if (device instanceof AndroidEmulator) {
        AndroidEmulator emulator = (AndroidEmulator) device;
        try {
            if (emulator.isEmulatorStarted()) {
                emulator.unlockEmulatorScreen();
            } else {
                Map<String, Object> config = new HashMap<String, Object>();
                if (serverConfiguration.getEmulatorOptions() != null) {
                    config.put(AndroidEmulator.EMULATOR_OPTIONS, serverConfiguration.getEmulatorOptions());
                }
                config.put(AndroidEmulator.TIMEOUT_OPTION, serverConfiguration.getTimeoutEmulatorStart());
                if (desiredCapabilities.asMap().containsKey(SelendroidCapabilities.DISPLAY)) {
                    Object d = desiredCapabilities.getCapability(SelendroidCapabilities.DISPLAY);
                    config.put(AndroidEmulator.DISPLAY_OPTION, String.valueOf(d));
                }

                Locale locale = parseLocale(desiredCapabilities);
                emulator.start(locale, deviceStore.nextEmulatorPort(), config);
            }
        } catch (AndroidDeviceException e) {
            deviceStore.release(device, app);
            if (retries > 0) {
                return createNewTestSession(caps, retries - 1);
            }
            throw new SessionNotCreatedException(
                    "Error occured while interacting with the emulator: " + emulator + ": " + e.getMessage());
        }
        emulator.setIDevice(deviceManager.getVirtualDevice(emulator.getAvdName()));
    }
    boolean appInstalledOnDevice = device.isInstalled(app);
    if (!appInstalledOnDevice || serverConfiguration.isForceReinstall()) {
        device.install(app);
    } else {
        log.info("the app under test is already installed.");
    }

    int port = getNextSelendroidServerPort();
    Boolean selendroidInstalledSuccessfully = device.isInstalled("io.selendroid." + app.getBasePackage());
    if (!selendroidInstalledSuccessfully || serverConfiguration.isForceReinstall()) {
        AndroidApp selendroidServer = createSelendroidServerApk(app);

        selendroidInstalledSuccessfully = device.install(selendroidServer);
        if (!selendroidInstalledSuccessfully) {
            if (!device.install(selendroidServer)) {
                deviceStore.release(device, app);

                if (retries > 0) {
                    return createNewTestSession(caps, retries - 1);
                }
            }
        }
    } else {
        log.info(
                "selendroid-server will not be created and installed because it already exists for the app under test.");
    }

    // Run any adb commands requested in the capabilities
    List<String> adbCommands = new ArrayList<String>();
    adbCommands.add("shell setprop log.tag.SELENDROID " + serverConfiguration.getLogLevel().name());
    adbCommands.addAll(desiredCapabilities.getPreSessionAdbCommands());

    for (String adbCommandParameter : adbCommands) {
        device.runAdbCommand(adbCommandParameter);
    }

    // It's GO TIME!
    // start the selendroid server on the device and make sure it's up
    try {
        device.startSelendroid(app, port);
    } catch (AndroidSdkException e) {
        log.info("error while starting selendroid: " + e.getMessage());

        deviceStore.release(device, app);
        if (retries > 0) {
            return createNewTestSession(caps, retries - 1);
        }
        throw new SessionNotCreatedException(
                "Error occurred while starting instrumentation: " + e.getMessage());
    }
    long start = System.currentTimeMillis();
    long startTimeOut = 20000;
    long timemoutEnd = start + startTimeOut;
    while (device.isSelendroidRunning() == false) {
        if (timemoutEnd >= System.currentTimeMillis()) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
        } else {
            throw new SelendroidException(
                    "Selendroid server on the device didn't came up after " + startTimeOut / 1000 + "sec:");
        }
    }

    // arbitrary sleeps? yay...
    // looks like after the server starts responding
    // we need to give it a moment before starting a session?
    try {
        Thread.sleep(500);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    // create the new session on the device server
    RemoteWebDriver driver;
    try {
        driver = new RemoteWebDriver(new URL("http://localhost:" + port + "/wd/hub"), desiredCapabilities);
    } catch (Exception e) {
        e.printStackTrace();
        deviceStore.release(device, app);
        throw new SessionNotCreatedException("Error occurred while creating session on Android device", e);
    }
    String sessionId = driver.getSessionId().toString();
    SelendroidCapabilities requiredCapabilities = new SelendroidCapabilities(driver.getCapabilities().asMap());
    ActiveSession session = new ActiveSession(sessionId, requiredCapabilities, app, device, port, this);

    this.sessions.put(sessionId, session);

    // We are requesting an "AndroidDriver" so automatically switch to the webview
    if (BrowserType.ANDROID.equals(desiredCapabilities.getAut())) {
        // arbitrarily high wait time, will this cover our slowest possible device/emulator?
        WebDriverWait wait = new WebDriverWait(driver, 60);
        // wait for the WebView to appear
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.webkit.WebView")));
        driver.switchTo().window("WEBVIEW");
        // the 'android-driver' webview has an h1 with id 'AndroidDriver' embedded in it
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AndroidDriver")));
    }

    return sessionId;
}

From source file:io.selendroid.server.model.SelendroidStandaloneDriverFixture.java

License:Apache License

protected static SelendroidServerBuilder getAndroidApkServerBuilder()
        throws IOException, ShellCommandException, AndroidSdkException {
    SelendroidServerBuilder builder = mock(SelendroidServerBuilder.class);
    AndroidApp server = mock(AndroidApp.class);
    AndroidApp resignedApp = mock(AndroidApp.class);
    when(resignedApp.getAppId()).thenReturn(BrowserType.ANDROID);

    when(builder/*from   w w  w. java2 s . co m*/
            .createSelendroidServer(new DefaultAndroidApp(new File(SelendroidStandaloneDriverTest.APK_FILE))))
                    .thenReturn(server);
    when(builder.resignApp(any(File.class))).thenReturn(resignedApp);
    return builder;
}

From source file:io.selendroid.server.model.SelendroidStandaloneDriverTest.java

License:Apache License

@Test
public void shouldInitDriverIfNoValidAppIsAvailable() throws Exception {
    SelendroidConfiguration conf = new SelendroidConfiguration();
    SelendroidStandaloneDriver driver = getSelendroidStandaloneDriver(getAndroidApkServerBuilder());

    driver.initApplicationsUnderTest(conf);

    Assert.assertTrue("Expecting only one app to be configured", driver.getConfiguredApps().size() == 1);
    Assert.assertEquals("Expecting AndroidDriver app to be configured",
            driver.getConfiguredApps().get(BrowserType.ANDROID).getAppId(), BrowserType.ANDROID);
}

From source file:io.selendroid.standalone.server.model.SelendroidStandaloneDriver.java

License:Apache License

void initApplicationsUnderTest(SelendroidConfiguration serverConfiguration)
        throws AndroidSdkException {
    if (serverConfiguration == null) {
        throw new SelendroidException("Configuration error - serverConfiguration can't be null.");
    }/*from   www .  j  av  a2  s  .  c  om*/
    this.serverConfiguration = serverConfiguration;

    // each of the apps specified on the command line need to get resigned
    // and 'stored' to be installed on the device
    for (String appPath : serverConfiguration.getSupportedApps()) {
        File file = new File(appPath);
        if (file.exists()) {
            addToAppsStore(file);
        } else {
            log.severe("Ignoring app because it was not found: " + file.getAbsolutePath());
        }
    }

    if (!serverConfiguration.isNoWebViewApp()) {
        // extract the 'AndroidDriver' app and show it as available
        try {
            // using "android" as the app name, because that is the desired capability default in
            // selenium for
            // DesiredCapabilities.ANDROID
            AndroidApp app = selendroidApkBuilder.resignApp(androidDriverAPKBuilder.extractAndroidDriverAPK());
            appsStore.put(BrowserType.ANDROID, app);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:io.selendroid.standalone.server.model.SelendroidStandaloneDriver.java

License:Apache License

public String createNewTestSession(JSONObject caps, Integer retries) {
    AndroidDevice device = null;/* ww  w .  j  av a  2s. co  m*/
    AndroidApp app = null;
    Exception lastException = null;
    while (retries >= 0) {
        try {
            SelendroidCapabilities desiredCapabilities = getSelendroidCapabilities(caps);
            String desiredAut = desiredCapabilities.getDefaultApp(appsStore.keySet());
            app = getAndroidApp(desiredCapabilities, desiredAut);
            log.info("'" + desiredAut + "' will be used as app under test.");
            device = deviceStore.findAndroidDevice(desiredCapabilities);

            // If we are using an emulator need to start it up
            if (device instanceof AndroidEmulator) {
                startAndroidEmulator(desiredCapabilities, (AndroidEmulator) device);
            }

            boolean appInstalledOnDevice = device.isInstalled(app) || app instanceof InstalledAndroidApp;
            if (!appInstalledOnDevice || serverConfiguration.isForceReinstall()) {
                device.install(app);
            } else {
                log.info("the app under test is already installed.");
            }

            if (!serverConfiguration.isNoClearData()) {
                device.clearUserData(app);
            }

            int port = getNextSelendroidServerPort();
            boolean serverInstalled = device.isInstalled("io.selendroid." + app.getBasePackage());
            if (!serverInstalled || serverConfiguration.isForceReinstall()) {
                try {
                    device.install(createSelendroidServerApk(app));
                } catch (AndroidSdkException e) {
                    throw new SessionNotCreatedException("Could not install selendroid-server on the device",
                            e);
                }
            } else {
                log.info(
                        "Not creating and installing selendroid-server because it is already installed for this app under test.");
            }

            // Run any adb commands requested in the capabilities
            List<String> preSessionAdbCommands = desiredCapabilities.getPreSessionAdbCommands();
            runPreSessionCommands(device, preSessionAdbCommands);

            // Push extension dex to device if specified
            String extensionFile = desiredCapabilities.getSelendroidExtensions();
            pushExtensionsToDevice(device, extensionFile);

            // Configure logging on the device
            device.setLoggingEnabled(serverConfiguration.isDeviceLog());

            // It's GO TIME!
            // start the selendroid server on the device and make sure it's up
            eventListener.onBeforeDeviceServerStart();
            device.startSelendroid(app, port, desiredCapabilities);
            waitForServerStart(device);
            eventListener.onAfterDeviceServerStart();

            // arbitrary sleeps? yay...
            // looks like after the server starts responding
            // we need to give it a moment before starting a session?
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }

            // create the new session on the device server
            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:" + port + "/wd/hub"),
                    desiredCapabilities);
            String sessionId = driver.getSessionId().toString();
            SelendroidCapabilities requiredCapabilities = new SelendroidCapabilities(
                    driver.getCapabilities().asMap());
            ActiveSession session = new ActiveSession(sessionId, requiredCapabilities, app, device, port, this);

            this.sessions.put(sessionId, session);

            // We are requesting an "AndroidDriver" so automatically switch to the webview
            if (BrowserType.ANDROID.equals(desiredCapabilities.getAut())) {
                switchToWebView(driver);
            }

            return sessionId;
        } catch (Exception e) {
            lastException = e;
            log.log(Level.SEVERE, "Error occurred while starting Selendroid session", e);
            retries--;

            // Return device to store
            if (device != null) {
                deviceStore.release(device, app);
                device = null;
            }
        }
    }

    if (lastException instanceof RuntimeException) {
        // Don't wrap the exception
        throw (RuntimeException) lastException;
    } else {
        throw new SessionNotCreatedException("Error starting Selendroid session", lastException);
    }
}