Search in sources :

Example 26 with DesiredCapabilities

use of org.openqa.selenium.remote.DesiredCapabilities in project cerberus-source by cerberustesting.

the class SeleniumServerService method setCapabilities.

/**
 * Set DesiredCapabilities
 *
 * @param tCExecution
 * @return
 * @throws CerberusException
 */
private DesiredCapabilities setCapabilities(TestCaseExecution tCExecution) throws CerberusException {
    /**
     * Instanciate DesiredCapabilities
     */
    DesiredCapabilities caps = new DesiredCapabilities();
    // In case browser is not defined at that level, we force it to firefox.
    if (StringUtil.isNullOrEmpty(tCExecution.getBrowser())) {
        tCExecution.setBrowser("firefox");
    }
    caps = this.setCapabilityBrowser(caps, tCExecution.getBrowser(), tCExecution);
    /**
     * Feed DesiredCapabilities with values get from Robot
     */
    if (!StringUtil.isNullOrEmpty(tCExecution.getPlatform())) {
        caps.setCapability("platform", tCExecution.getPlatform());
    }
    if (!StringUtil.isNullOrEmpty(tCExecution.getVersion())) {
        caps.setCapability("version", tCExecution.getVersion());
    }
    /**
     * Loop on RobotCapabilities to feed DesiredCapabilities Capability must
     * be String, Integer or Boolean
     */
    List<RobotCapability> additionalCapabilities = tCExecution.getCapabilities();
    if (additionalCapabilities != null) {
        for (RobotCapability additionalCapability : additionalCapabilities) {
            if (StringUtil.isBoolean(additionalCapability.getValue())) {
                caps.setCapability(additionalCapability.getCapability(), StringUtil.parseBoolean(additionalCapability.getValue()));
            } else if (StringUtil.isInteger(additionalCapability.getValue())) {
                caps.setCapability(additionalCapability.getCapability(), Integer.valueOf(additionalCapability.getValue()));
            } else {
                caps.setCapability(additionalCapability.getCapability(), additionalCapability.getValue());
            }
        }
    }
    /**
     * if application is a mobile one, then set the "app" capability to the
     * application binary path
     */
    if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK) || tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {
        // Set the app capability with the application path
        if (tCExecution.isManualURL()) {
            caps.setCapability("app", tCExecution.getMyHost());
        } else {
            caps.setCapability("app", tCExecution.getCountryEnvironmentParameters().getIp());
        }
    }
    return caps;
}
Also used : DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) RobotCapability(org.cerberus.crud.entity.RobotCapability)

Example 27 with DesiredCapabilities

use of org.openqa.selenium.remote.DesiredCapabilities in project cerberus-source by cerberustesting.

the class SeleniumServerService method startServer.

@Override
public void startServer(TestCaseExecution tCExecution) throws CerberusException {
    // message used for log purposes
    String logPrefix = "[" + tCExecution.getTest() + " - " + tCExecution.getTestCase() + "] ";
    try {
        LOG.info(logPrefix + "Start Robot Server (Selenium, Appium or Sikuli)");
        /**
         * Set Session
         */
        LOG.debug(logPrefix + "Setting the session.");
        String system = tCExecution.getApplicationObj().getSystem();
        /**
         * Get the parameters that will be used to set the servers
         * (selenium/appium) If timeout has been defined at the execution
         * level, set the selenium & appium wait element with this value,
         * else, take the one from parameter
         */
        Integer cerberus_selenium_pageLoadTimeout, cerberus_selenium_implicitlyWait, cerberus_selenium_setScriptTimeout, cerberus_selenium_wait_element, cerberus_appium_wait_element, cerberus_selenium_action_click_timeout;
        if (!tCExecution.getTimeout().isEmpty()) {
            cerberus_selenium_wait_element = Integer.valueOf(tCExecution.getTimeout());
            cerberus_appium_wait_element = Integer.valueOf(tCExecution.getTimeout());
        } else {
            cerberus_selenium_wait_element = parameterService.getParameterIntegerByKey("cerberus_selenium_wait_element", system, 90000);
            cerberus_appium_wait_element = parameterService.getParameterIntegerByKey("cerberus_appium_wait_element", system, 90000);
        }
        cerberus_selenium_pageLoadTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_pageLoadTimeout", system, 90000);
        cerberus_selenium_implicitlyWait = parameterService.getParameterIntegerByKey("cerberus_selenium_implicitlyWait", system, 0);
        cerberus_selenium_setScriptTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_setScriptTimeout", system, 90000);
        cerberus_selenium_action_click_timeout = parameterService.getParameterIntegerByKey("cerberus_selenium_action_click_timeout", system, 90000);
        LOG.debug(logPrefix + "TimeOut defined on session : " + cerberus_selenium_wait_element);
        Session session = new Session();
        session.setCerberus_selenium_implicitlyWait(cerberus_selenium_implicitlyWait);
        session.setCerberus_selenium_pageLoadTimeout(cerberus_selenium_pageLoadTimeout);
        session.setCerberus_selenium_setScriptTimeout(cerberus_selenium_setScriptTimeout);
        session.setCerberus_selenium_wait_element(cerberus_selenium_wait_element);
        session.setCerberus_appium_wait_element(cerberus_appium_wait_element);
        session.setCerberus_selenium_action_click_timeout(cerberus_selenium_action_click_timeout);
        session.setHost(tCExecution.getSeleniumIP());
        session.setHostUser(tCExecution.getSeleniumIPUser());
        session.setHostPassword(tCExecution.getSeleniumIPPassword());
        session.setPort(tCExecution.getPort());
        tCExecution.setSession(session);
        LOG.debug(logPrefix + "Session is set.");
        /**
         * SetUp Capabilities
         */
        LOG.debug(logPrefix + "Set Capabilities");
        DesiredCapabilities caps = this.setCapabilities(tCExecution);
        session.setDesiredCapabilities(caps);
        LOG.debug(logPrefix + "Set Capabilities - retreived");
        /**
         * SetUp Proxy
         */
        String hubUrl = StringUtil.cleanHostURL(SeleniumServerService.getBaseUrl(StringUtil.formatURLCredential(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword()) + session.getHost(), session.getPort())) + "/wd/hub";
        LOG.debug(logPrefix + "Hub URL :" + hubUrl);
        URL url = new URL(hubUrl);
        HttpCommandExecutor executor = null;
        boolean isProxy = proxyService.useProxy(hubUrl, system);
        if (isProxy) {
            String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
            int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);
            HttpClientBuilder builder = HttpClientBuilder.create();
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            builder.setProxy(proxy);
            if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {
                String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);
                String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
                if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
                    credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword()));
                }
                builder.setDefaultCredentialsProvider(credsProvider);
            }
            Factory factory = new MyHttpClientFactory(builder);
            executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);
        }
        /**
         * SetUp Driver
         */
        LOG.debug(logPrefix + "Set Driver");
        WebDriver driver = null;
        AppiumDriver appiumDriver = null;
        if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)) {
            if (caps.getPlatform().is(Platform.ANDROID)) {
                if (executor == null) {
                    appiumDriver = new AndroidDriver(url, caps);
                } else {
                    appiumDriver = new AndroidDriver(executor, caps);
                }
                driver = (WebDriver) appiumDriver;
            } else if (caps.getPlatform().is(Platform.MAC)) {
                if (executor == null) {
                    appiumDriver = new IOSDriver(url, caps);
                } else {
                    appiumDriver = new IOSDriver(executor, caps);
                }
                driver = (WebDriver) appiumDriver;
            } else // Any Other
            {
                if (executor == null) {
                    driver = new RemoteWebDriver(url, caps);
                } else {
                    driver = new RemoteWebDriver(executor, caps);
                }
            }
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {
            if (executor == null) {
                appiumDriver = new AndroidDriver(url, caps);
            } else {
                appiumDriver = new AndroidDriver(executor, caps);
            }
            driver = (WebDriver) appiumDriver;
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {
            if (executor == null) {
                appiumDriver = new IOSDriver(url, caps);
            } else {
                appiumDriver = new IOSDriver(executor, caps);
            }
            driver = (WebDriver) appiumDriver;
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_FAT)) {
            /**
             * Check sikuli extension is reachable
             */
            if (!sikuliService.isSikuliServerReachable(session)) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);
                mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));
                mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));
                throw new CerberusException(mes);
            }
            /**
             * If CountryEnvParameter IP is set, open the App
             */
            if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {
                sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());
            }
        }
        /**
         * Defining the timeout at the driver level. Only in case of not
         * Appium Driver (see
         * https://github.com/vertigo17/Cerberus/issues/754)
         */
        if (driver != null && appiumDriver == null) {
            driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);
            driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);
            driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);
        }
        tCExecution.getSession().setDriver(driver);
        tCExecution.getSession().setAppiumDriver(appiumDriver);
        /**
         * If Gui application, maximize window Get IP of Node in case of
         * remote Server. Maximize does not work for chrome browser We also
         * get the Real UserAgent from the browser.
         */
        if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI) && !caps.getPlatform().equals(Platform.ANDROID)) {
            if (!caps.getBrowserName().equals(BrowserType.CHROME)) {
                driver.manage().window().maximize();
            }
            getIPOfNode(tCExecution);
            /**
             * If screenSize is defined, set the size of the screen.
             */
            String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());
            LOG.debug("Selenium resolution : " + targetScreensize);
            if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {
                Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);
                Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);
                setScreenSize(driver, screenWidth, screenLength);
                LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);
            }
            tCExecution.setScreenSize(getScreenSize(driver));
            tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));
            String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
            tCExecution.setUserAgent(userAgent);
        }
        tCExecution.getSession().setStarted(true);
    } catch (CerberusException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        throw new CerberusException(exception.getMessageError());
    } catch (MalformedURLException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);
        mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));
        throw new CerberusException(mes);
    } catch (UnreachableBrowserException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);
        mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));
        mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));
        mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));
        throw new CerberusException(mes);
    } catch (Exception exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
        mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));
        throw new CerberusException(mes);
    }
}
Also used : WebDriver(org.openqa.selenium.WebDriver) RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) Factory(org.openqa.selenium.remote.http.HttpClient.Factory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) AndroidDriver(io.appium.java_client.android.AndroidDriver) URL(java.net.URL) HttpCommandExecutor(org.openqa.selenium.remote.HttpCommandExecutor) IOSDriver(io.appium.java_client.ios.IOSDriver) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) HttpHost(org.apache.http.HttpHost) CerberusException(org.cerberus.exception.CerberusException) AppiumDriver(io.appium.java_client.AppiumDriver) RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Point(org.openqa.selenium.Point) JSONException(org.json.JSONException) CerberusException(org.cerberus.exception.CerberusException) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) AuthScope(org.apache.http.auth.AuthScope) Session(org.cerberus.engine.entity.Session)

Example 28 with DesiredCapabilities

use of org.openqa.selenium.remote.DesiredCapabilities in project jmeter-plugins by undera.

the class ChromeDriverConfig method createCapabilities.

Capabilities createCapabilities() {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(CapabilityType.PROXY, createProxy());
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.BROWSER, Level.ALL);
    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
    if (isAndroidEnabled() || isHeadlessEnabled()) {
        // Map<String, String> chromeOptions = new HashMap<String, String>();
        // chromeOptions.put("androidPackage", "com.android.chrome");
        ChromeOptions chromeOptions = new ChromeOptions();
        if (isAndroidEnabled()) {
            chromeOptions.setExperimentalOption("androidPackage", "com.android.chrome");
        }
        if (isHeadlessEnabled()) {
            chromeOptions.addArguments("--headless");
        }
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    }
    return capabilities;
}
Also used : DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) LoggingPreferences(org.openqa.selenium.logging.LoggingPreferences) ChromeOptions(org.openqa.selenium.chrome.ChromeOptions)

Example 29 with DesiredCapabilities

use of org.openqa.selenium.remote.DesiredCapabilities in project jmeter-plugins by undera.

the class RemoteDriverConfig method createCapabilities.

Capabilities createCapabilities() {
    DesiredCapabilities capabilities = RemoteDesiredCapabilitiesFactory.build(getCapability());
    capabilities.setCapability(CapabilityType.PROXY, createProxy());
    capabilities.setJavascriptEnabled(true);
    return capabilities;
}
Also used : DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities)

Example 30 with DesiredCapabilities

use of org.openqa.selenium.remote.DesiredCapabilities in project selenium_java by sergueik.

the class ChromePagePerformanceTest method beforeClass.

@SuppressWarnings("deprecation")
@BeforeClass
public static void beforeClass() throws IOException {
    getOsName();
    System.setProperty("webdriver.chrome.driver", osName.toLowerCase().startsWith("windows") ? new File("c:/java/selenium/chromedriver.exe").getAbsolutePath() : "/var/run/chromedriver");
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions options = new ChromeOptions();
    Map<String, Object> chromePrefs = new HashMap<>();
    chromePrefs.put("profile.default_content_settings.popups", 0);
    String downloadFilepath = System.getProperty("user.dir") + System.getProperty("file.separator") + "target" + System.getProperty("file.separator");
    chromePrefs.put("download.default_directory", downloadFilepath);
    chromePrefs.put("enableNetwork", "true");
    options.setExperimentalOption("prefs", chromePrefs);
    for (String option : (new String[] { "allow-running-insecure-content", "allow-insecure-localhost", "enable-local-file-accesses", "disable-notifications", /* "start-maximized" , */
    "browser.download.folderList=2", "--browser.helperApps.neverAsk.saveToDisk=image/jpg,text/csv,text/xml,application/xml,application/vnd.ms-excel,application/x-excel,application/x-msexcel,application/excel,application/pdf", String.format("browser.download.dir=%s", downloadFilepath) /* "user-data-dir=/path/to/your/custom/profile"  , */
    })) {
        options.addArguments(option);
    }
    // options for headless
    if (headless) {
        // headless option arguments
        for (String option : (osName.toLowerCase().startsWith("windows")) ? new String[] { "headless", "disable-gpu", "disable-plugins", "window-size=1200x600", "window-position=-9999,0" } : new String[] { "headless", "disable-gpu", "remote-debugging-port=9222", "window-size=1200x600" }) {
            options.addArguments(option);
        }
    // on Windows need ChromeDriver 2.31 / Chrome 60 to support headless
    // With earlier versions of chromedriver: chrome not reachable...
    // https://developers.google.com/web/updates/2017/04/headless-chrome
    // https://stackoverflow.com/questions/43880619/headless-chrome-and-selenium-on-windows
    }
    capabilities.setBrowserName(DesiredCapabilities.chrome().getBrowserName());
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    driver = new ChromeDriver(capabilities);
    try {
        // origin:
        // https://www.tutorialspoint.com/sqlite/sqlite_java.htm
        Class.forName("org.sqlite.JDBC");
        // String dbURL = "jdbc:sqlite:performance.db";
        conn = DriverManager.getConnection("jdbc:sqlite:performance.db");
        if (conn != null) {
            // System.out.println("Connected to the database");
            DatabaseMetaData databaseMetadata = conn.getMetaData();
            // System.out.println("Driver name: " +
            // databaseMetadata.getDriverName());
            // System.out.println("Driver version: " +
            // databaseMetadata.getDriverVersion());
            // System.out.println("Product name: " +
            // databaseMetadata.getDatabaseProductName());
            // System.out.println("Product version: " +
            // databaseMetadata.getDatabaseProductVersion());
            createNewTable();
        // insertData("name", 1.0);
        // conn.close();
        }
    } catch (ClassNotFoundException | SQLException ex) {
        ex.printStackTrace();
    } finally {
    }
    assertThat(driver, notNullValue());
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) ChromeOptions(org.openqa.selenium.chrome.ChromeOptions) ChromePagePerformanceObject(org.utils.ChromePagePerformanceObject) ChromeDriver(org.openqa.selenium.chrome.ChromeDriver) DatabaseMetaData(java.sql.DatabaseMetaData) File(java.io.File) BeforeClass(org.junit.BeforeClass)

Aggregations

DesiredCapabilities (org.openqa.selenium.remote.DesiredCapabilities)178 File (java.io.File)55 ChromeDriver (org.openqa.selenium.chrome.ChromeDriver)40 URL (java.net.URL)34 HashMap (java.util.HashMap)34 RemoteWebDriver (org.openqa.selenium.remote.RemoteWebDriver)30 ChromeOptions (org.openqa.selenium.chrome.ChromeOptions)29 Test (org.testng.annotations.Test)22 FirefoxDriver (org.openqa.selenium.firefox.FirefoxDriver)20 BeforeClass (org.junit.BeforeClass)19 TestSetup (com.coveros.selenified.utilities.TestSetup)17 FirefoxProfile (org.openqa.selenium.firefox.FirefoxProfile)17 PhantomJSDriver (org.openqa.selenium.phantomjs.PhantomJSDriver)16 WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait)14 MalformedURLException (java.net.MalformedURLException)13 Before (org.junit.Before)13 Test (org.junit.Test)13 InternetExplorerDriver (org.openqa.selenium.ie.InternetExplorerDriver)12 Actions (org.openqa.selenium.interactions.Actions)12 Dimension (org.openqa.selenium.Dimension)11