org.openqa.selenium.remote.RemoteWebDriver Java Examples

The following examples show how to use org.openqa.selenium.remote.RemoteWebDriver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BrowserService.java    From collect-earth with MIT License 6 votes vote down vote up
private boolean loadPlotInDGMap(SimplePlacemarkObject placemarkObject, RemoteWebDriver driver)
		throws InterruptedException {

	boolean success = true;
	if (driver != null && waitFor("mainContent", driver) && driver instanceof JavascriptExecutor) {
		try {
			String dgmapJs = getDGMapJavascript(placemarkObject);
			driver.executeScript(dgmapJs);

			Thread.sleep( 1000 );
			// Unlock the view if it is locked
			if( isCssElementPresent(".lock.on",  driver)  ) {
				driver.findElementByCssSelector(".lock.on").click(); // UNLOCK
			}

		} catch (final Exception e) {
			processSeleniumError(e);
			success = false;
		}
	}
	return success;
}
 
Example #2
Source File: ButtonTest.java    From adf-selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void testWindowPopupButton() {
    RemoteWebDriver webdriver = driver.getDriver();
    ButtonDemoPage page = pages.goHome();

    DialogManager dialogManager = driver.getDialogManager();
    assertEquals(0, dialogManager.totalNumberOfDialogsOpen());
    assertNull(dialogManager.getCurrentDialog());

    // find an click af:button with useWindow='true'
    NewFileWindowDialog dialog = page.clickUseWindowButton(); // opens popup in new browser window

    // verify new dialog is opened and active
    assertEquals(1, dialogManager.totalNumberOfDialogsOpen());
    Dialog firstDialog = dialogManager.getCurrentDialog();
    assertNotNull(firstDialog);
    assertEquals("New File", firstDialog.getTitle(webdriver));

    // close dialog by clicking Save button in dialog
    dialog.findSaveButton().clickWithDialogDetect();
    assertEquals(0, dialogManager.totalNumberOfDialogsOpen());
}
 
Example #3
Source File: DesktopFactory.java    From carina with Apache License 2.0 6 votes vote down vote up
@Override
public String getVncURL(WebDriver driver) {
    String vncURL = null;
    if (driver instanceof RemoteWebDriver && "true".equals(Configuration.getCapability("enableVNC"))) {
        // TODO: resolve negative case when VNC is not supported
        final RemoteWebDriver rwd = (RemoteWebDriver) driver;
        String protocol = R.CONFIG.get(vnc_protocol);
        String host = R.CONFIG.get(vnc_host);
        String port = R.CONFIG.get(vnc_port);
        // If VNC host/port not set user them from Selenium
        if (StringUtils.isEmpty(host) || StringUtils.isEmpty(port)) {
            host = ((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getHost();
            port = String.valueOf(((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getPort());
        }
        vncURL = String.format(R.CONFIG.get("vnc_desktop"), protocol, host, port, rwd.getSessionId().toString());
    }
    return vncURL;
}
 
Example #4
Source File: BackAction.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean _executeAction( WebDriver webDriver, List<Object> parameterList )
{
	String deviceName = getDeviceName( webDriver );
	Handset localDevice = PerfectoMobile.instance(( (DeviceWebDriver) webDriver ).getxFID() ).devices().getDevice( deviceName );

	if ( (localDevice.getOs().toLowerCase().equals( "android" )) && (webDriver instanceof DeviceWebDriver) )
	{
		try
		{
			Map<String, Object> params = new HashMap<>();
			params.put("keySequence", "BACK");
			((RemoteWebDriver) ((DeviceWebDriver) webDriver).getWebDriver()).executeScript("mobile:presskey", params);
		}
		catch ( Throwable e )
		{
			log.error("Failed to press BACK key.");
		}
	}
	else
	{
		webDriver.navigate().back();
	}
	return true;
}
 
Example #5
Source File: LocalServerWebDriverContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void testConnection() {
    // getWebDriver {
    RemoteWebDriver driver = chrome.getWebDriver();
    // }

    // Construct a URL that the browser container can access
    // getPage {
    String hostIpAddress = chrome.getTestHostIpAddress();
    driver.get("http://" + hostIpAddress + ":" + localPort);
    // }

    String headingText = driver.findElement(By.cssSelector("h1")).getText().trim();

    assertEquals("The hardcoded success message was found on a page fetched from a local server", "It worked", headingText);
}
 
Example #6
Source File: SeleniumTestUtilities.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
public static WebDriver getFirefoxDriver()
            throws Exception
	{
        baseDir = new File(".").getPath();
        System.out.println("******** " + baseDir);

        String path = "src/test/resources/geckodriver";
        System.out.println("******** " + path);
		System.setProperty("webdriver.gecko.driver", path);

        DesiredCapabilities capabilities =  DesiredCapabilities.firefox();
		capabilities.setCapability("marionette", true);
        capabilities.setCapability("networkConnectionEnabled", true);
        capabilities.setCapability("browserConnectionEnabled", true);


        WebDriver driver = new RemoteWebDriver(
                new URL("http://localhost:4444"),
                capabilities);

//		WebDriver driver = new MarionetteDriver(capabilities);

		return driver;
	}
 
Example #7
Source File: MyTest.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public void test() {
		SelendroidCapabilities capa = new SelendroidCapabilities(TEST_APP_ID);
		capa.setLaunchActivity("com.eg.android.AlipayGphone.AlipayLogin");
		WebDriver driver = new RemoteWebDriver(capa);
		//driver.switchTo().window("NATIVE_APP");//
		WebElement inputField = driver.findElement(By.id("buttonStartWebview"));
		inputField.click();
		
		driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

		System.out.println("============================================");
		WebDriver webDriver = driver.switchTo().window("WEBVIEW_0");
		System.out.println("=====================3432=======================");
		webDriver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
		System.out.println("getWindowHandle:" + webDriver.getPageSource());
		//WebElement element3 = webDriver.findElement(By.xpath("//input[@value='Send me your name!']"));
		WebElement element3 = webDriver.findElement(By.xpath("//input[@id='name_input']"));
		element3.sendKeys("he zheng");
		//element3.clear();

		webDriver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
//		inputField.sendKeys("Selendroid");
//		Assert.assertEquals("Selendroid", inputField.getText());
		//driver.quit();
	}
 
Example #8
Source File: GridInterface.java    From candybean with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void start() throws CandybeanException {
	capabilities.setBrowserName(candybean.config.getValue("grid.browser"));
	capabilities.setCapability("platform",candybean.config.getValue("grid.platform"));
	String ip = candybean.config.getValue("grid.ip");
	String port = candybean.config.getValue("grid.port");
	logger.info("Starting interface with ip " + ip + " and port " + port);
	try {
		URL url = new URL("http://" + ip + ":" + port +  "/wd/hub");
		System.out.println(url.toString());
		wd = new RemoteWebDriver(url, capabilities);
	} catch (MalformedURLException e) {
		throw new CandybeanException(e);
	}
	super.start(); // requires wd to be instantiated first
}
 
Example #9
Source File: CustomDriverProvider.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * Задает capabilities для запуска Remote драйвера для Selenoid
 *
 * @param capabilities - capabilities для установленного браузера
 * @param remoteUrl    - url для запуска тестов, например http://remoteIP:4444/wd/hub
 * @return WebDriver
 */
private WebDriver getRemoteDriver(MutableCapabilities capabilities, String remoteUrl) {
    log.info("---------------run Remote Driver---------------------");
    Boolean isSelenoidRun = loadSystemPropertyOrDefault(SELENOID, true);
    if (isSelenoidRun) {
        capabilities.setCapability("enableVNC", true);
        capabilities.setCapability("screenResolution", String.format("%sx%s", loadSystemPropertyOrDefault(WINDOW_WIDTH, DEFAULT_WIDTH),
                loadSystemPropertyOrDefault(WINDOW_HEIGHT, DEFAULT_HEIGHT)));
        String sessionName = loadSystemPropertyOrDefault(SELENOID_SESSION_NAME, "");
        if (!sessionName.isEmpty()) {
            capabilities.setCapability("name", String.format("%s %s", sessionName, AkitaScenario.getInstance().getScenario().getName()));
        }
    }
    try {
        RemoteWebDriver remoteWebDriver = new RemoteWebDriver(
            URI.create(remoteUrl).toURL(),
            capabilities
        );
        remoteWebDriver.setFileDetector(new LocalFileDetector());
        return remoteWebDriver;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: BrowserStatement.java    From neodymium-library with MIT License 6 votes vote down vote up
private boolean isWebDriverStillOpen(WebDriver webDriver)
{
    if (webDriver == null)
    {
        return false;
    }
    try
    {
        RemoteWebDriver driver = (RemoteWebDriver) ((EventFiringWebDriver) webDriver).getWrappedDriver();
        return driver.getSessionId() != null;
    }
    catch (Exception e)
    {
        LOGGER.warn("Couldn't detect if the WebDriver is still open!", e);
        return true;
    }
}
 
Example #11
Source File: JavaDriverTest.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public void javaDriver() {
    driver = new JavaDriver();
    Capabilities capabilities = ((RemoteWebDriver) driver).getCapabilities();
    AssertJUnit.assertEquals("java", capabilities.getBrowserName());
    AssertJUnit.assertEquals(true, capabilities.is("takesScreenshot"));
    AssertJUnit.assertEquals(false, capabilities.is("nativeEvents"));
}
 
Example #12
Source File: WebDriverAftBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
     * Failures in testSetup cause the test to not be recorded.  Future plans are to extract form @Before and call at the start of each test.
     * Setup the WebDriver properties, test, and login.  Named testSetUp so it runs after TestNG's startSession(Method)
     * {@link WebDriverUtils#determineUser(String)}
     * {@link WebDriverUtils#setUp(String, String, String, String)}
     */
    @Before
    public void testSetUp() {
        // TODO it would be better if all opening of urls and logging in was not done in setUp, failures in setUp case the test to not be recorded. extract to setUp and call first for all tests.
        try { // Don't throw any exception from this methods, exceptions in Before annotations really mess up maven, surefire, or failsafe
            setUpSetUp();

            driver = WebDriverUtils.setUp(getClass().getSimpleName(), testMethodName); // one browser comment this out

            String testUrl = getTestUrl();
            // TODO Got into the situation where the first url doesn't expect server, but all others do.  Readdress once
            // the NavIT WDIT conversion has been completed.
            if (!testUrl.startsWith("http")) {
                testUrl = getBaseUrlString() + testUrl;
            }
            WebDriverUtils.openTestUrl(driver, testUrl);

//            oneBrowserHandle = driver.getWindowHandle(); // one browser other windows will be closed
//            System.out.println("One Browser handle " + oneBrowserHandle);
//            closeAllOtherWindows(oneBrowserHandle); // close all others than one browser

            this.sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
            System.out.println(jGrowlHeader + " sessionId is " + sessionId);

//            if (isVisible(By.name("login_user"))) { // one browser
                login(driver, getUserName(), this);
//            }

            navigateInternal(); // SeleniumBaseTest.fail from navigateInternal results in the test not being recorded as a failure in CI.

            javascriptErrorsReport();

        } catch (Throwable t) {
            System.out.println("Throwable " + t.getMessage() + " in Before annotated method is very bad, ignoring and letting first method of test class to fail.");
            t.printStackTrace();
            System.out.println("Throwable " + t.getMessage()
                    + " in Before annotated method is very bad, ignoring and letting first method of test class to fail.");
        }
    }
 
Example #13
Source File: Browser.java    From selenium-shutterbug with MIT License 5 votes vote down vote up
private void defineCustomCommand(String name, CommandInfo info) {
    try {
        Method defineCommand = HttpCommandExecutor.class.getDeclaredMethod("defineCommand", String.class, CommandInfo.class);
        defineCommand.setAccessible(true);
        defineCommand.invoke(((RemoteWebDriver) this.driver).getCommandExecutor(), name, info);
    } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: AppiumIosTest.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSessions() throws Exception {
    HttpGet request = new HttpGet("http://localhost:4723/wd/hub/sessions");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));
    String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    assertEquals(sessionId, jsonObject.get("sessionId"));
    httpClient.close();
}
 
Example #15
Source File: Edition054_Selenium_Grid_Android.java    From appiumpro with Apache License 2.0 5 votes vote down vote up
@Test
public void testAndroid() throws MalformedURLException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("platformName", "Android");
    caps.setCapability("deviceName", "Android Emulator");
    caps.setCapability("automationName", "UiAutomator2");
    caps.setCapability("browserName", "Chrome");

    driver = new RemoteWebDriver(new URL(HUB_URL), caps);
    actualTest(driver);
}
 
Example #16
Source File: BrowserDetectionImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@Override
public boolean isIPad(@NotNull final WebDriver webDriver) {
	return webDriver instanceof RemoteWebDriver
		&& ((RemoteWebDriver) webDriver).getCapabilities()
		.getBrowserName()
		.equalsIgnoreCase(IPAD_BROWSER_NAME);
}
 
Example #17
Source File: DriverFactory.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
private void instantiateWebDriver(DriverType driverType) throws MalformedURLException {
    System.out.println(" ");
    System.out.println("Local Operating System: " + operatingSystem);
    System.out.println("Local Architecture: " + systemArchitecture);
    System.out.println("Selected Browser: " + selectedDriverType);
    System.out.println("Connecting to Selenium Grid: " + useRemoteWebDriver);
    System.out.println(" ");

    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();

    if (useRemoteWebDriver) {
        URL seleniumGridURL = new URL(System.getProperty("gridURL"));
        String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");
        String desiredPlatform = System.getProperty("desiredPlatform");

        if (null != desiredPlatform && !desiredPlatform.isEmpty()) {
            desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));
        }

        if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {
            desiredCapabilities.setVersion(desiredBrowserVersion);
        }

        desiredCapabilities.setBrowserName(selectedDriverType.toString());
        webDriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);
    } else {
        webDriver = driverType.getWebDriverObject(desiredCapabilities);
    }
}
 
Example #18
Source File: ScreenshotUtils.java    From JTAF-ExtWebDriver with Apache License 2.0 5 votes vote down vote up
/***
 * Take a screenshot of the browser content. Note that while using RemoteWebDriver sessions (ie: with
 * Sauce Labs), the screenshot will be a full page of content--not only the visible content where the
 * page is scrolled (as when using a non-RemoteWebDriver session).
 * 
 * @param toSaveAs - name of the file to save the picture in (Note: must be PNG)
 * @throws IOException 
 */
public static void takeScreenshotOfPage(File toSaveAs) throws IOException {
	WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver();
	File screenshot;
	if(!(wd instanceof RemoteWebDriver)) {
		screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);		
	}
	else {
		Augmenter augmenter = new Augmenter();
		screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
	}
	FileUtils.copyFile(screenshot, toSaveAs);
}
 
Example #19
Source File: VisualAssertion.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Returns the browser name using Selenium methods
 * 
 * @param webDriver
 *            the WebDriver to query
 * @return the browser name
 */
private String getBrowserName(final WebDriver webDriver)
{
    final Capabilities capabilities = ((RemoteWebDriver) webDriver).getCapabilities();
    final String browserName = capabilities.getBrowserName();

    return browserName == null ? "unknown" : browserName;
}
 
Example #20
Source File: DeviceWebDriver.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
public Set<String> getContextHandles()
{
    setLastAction();
    if ( contextHandles != null )
        return contextHandles;

    RemoteExecuteMethod executeMethod = new RemoteExecuteMethod( (RemoteWebDriver) webDriver );
    List<String> handleList = (List<String>) executeMethod.execute( DriverCommand.GET_CONTEXT_HANDLES, null );

    contextHandles = new HashSet<String>( 10 );
    contextHandles.addAll( handleList );
    return contextHandles;
}
 
Example #21
Source File: DriverFactory.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
private void instantiateWebDriver(DriverType driverType) throws MalformedURLException {
    System.out.println(" ");
    System.out.println("Local Operating System: " + operatingSystem);
    System.out.println("Local Architecture: " + systemArchitecture);
    System.out.println("Selected Browser: " + selectedDriverType);
    System.out.println("Connecting to Selenium Grid: " + useRemoteWebDriver);
    System.out.println(" ");

    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();

    if (useRemoteWebDriver) {
        URL seleniumGridURL = new URL(System.getProperty("gridURL"));
        String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");
        String desiredPlatform = System.getProperty("desiredPlatform");

        if (null != desiredPlatform && !desiredPlatform.isEmpty()) {
            desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));
        }

        if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {
            desiredCapabilities.setVersion(desiredBrowserVersion);
        }

        desiredCapabilities.setBrowserName(selectedDriverType.toString());
        webDriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);
    } else {
        webDriver = driverType.getWebDriverObject(desiredCapabilities);
    }
}
 
Example #22
Source File: UpdateSauceStatusTest.java    From demo-java with MIT License 5 votes vote down vote up
public void setUp() throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ChromeOptions.CAPABILITY,  chromeOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "googlechrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example #23
Source File: RedeployLeakIT.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void deployUseUndeployCheck() throws Exception {
    // DO NOT RUN FROM ECLIPSE
    // The test uses files from the target folder
    setup(7778);
    RemoteWebDriver driver = new RemoteWebDriver(Browser.CHROME.getDesiredCapabilities());
    try {
        driver.get("http://"+ getCurrentHostAddress() + ":7778/");
        Assert.assertNotNull(driver.findElement(By.id("hello")));
    } finally {
        driver.close();
        driver.quit();
    }
    shutdownAndVerify();
}
 
Example #24
Source File: RemoteWebDriverTest.java    From mastering-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
void testWithRemoteChrome(
        @DriverUrl("http://localhost:4444/wd/hub") @DriverCapabilities({
                "browserName=chrome",
                "version=59" }) RemoteWebDriver remoteChrome) {

    remoteChrome.get("https://bonigarcia.github.io/selenium-jupiter/");

    assertTrue(remoteChrome.getTitle().contains("JUnit 5 extension"));
}
 
Example #25
Source File: SeleniumElement.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
public boolean _press()
{
  WebElement webElement = getElement();
  if (webElement != null && webElement.getSize().getHeight() > 0 && webElement.getSize().getWidth() > 0)
  {
    if (getWebDriver() instanceof HasInputDevices)
    {
      if (isTimed())
        getActionProvider().startTimer((DeviceWebDriver) getWebDriver(), this, getExecutionContext());

      if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof AppiumDriver)
      {
        new TouchAction((AppiumDriver) ((DeviceWebDriver) getWebDriver()).getNativeDriver()).press(createPoint(webElement)).perform();
      }
      else if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof RemoteWebDriver)
      {
        if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof HasTouchScreen)
          new TouchActions(getWebDriver()).clickAndHold(webElement).build().perform();
        else
          new Actions(getWebDriver()).clickAndHold(webElement).build().perform();
      }

      return true;
    }
  }

  return false;
}
 
Example #26
Source File: ServerJupiterTest.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("capabilitesProvider")
void testServer(Capabilities capabilities) throws MalformedURLException {
    String serverUrl = String.format("http://localhost:%s/wd/hub/",
            serverPort);
    RemoteWebDriver driver = new RemoteWebDriver(new URL(serverUrl),
            capabilities);
    assertNotNull(driver);
    driver.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver.getTitle(),
            containsString("JUnit 5 extension for Selenium"));
    driver.quit();
    assertNull(driver.getSessionId());
}
 
Example #27
Source File: WebDriverDecorator.java    From teasy with MIT License 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(final OutputType<X> target) throws WebDriverException {
    if (driver.getClass() == RemoteWebDriver.class) {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        return ((TakesScreenshot) augmentedDriver).getScreenshotAs(target);
    } else {
        return ((TakesScreenshot) driver).getScreenshotAs(target);
    }
}
 
Example #28
Source File: Device.java    From agent with MIT License 5 votes vote down vote up
public RemoteWebDriver freshDriver(Capabilities caps, boolean merge) {
    if (!deviceServer.isAvailable(30)) {
        deviceServer.restart();
    }

    quitDriver();
    setCaps(caps, merge);
    driver = newDriver();
    return driver;
}
 
Example #29
Source File: DriverFactory.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
public RemoteWebDriver getDriver(boolean useBrowserMobProxy) throws MalformedURLException {
    if (useBrowserMobProxy != usingBrowserMobProxy) {
        quitDriver();
    }
    if (null == webDriver) {
        instantiateWebDriver(selectedDriverType, useBrowserMobProxy);
    }

    return webDriver;
}
 
Example #30
Source File: Module2JunitTest.java    From demo-java with MIT License 5 votes vote down vote up
@Test
public void shouldOpenSafari() throws MalformedURLException {
    /** Here we set environment variables from your local machine, or IntelliJ run configuration,
     *  and store these values in the variables below. Doing this is a best practice in terms of test execution
     *  and security. If you're not sure how to use env variables, refer to this guide -
     * https://wiki.saucelabs.com/display/DOCS/Best+Practice%3A+Use+Environment+Variables+for+Authentication+Credentials
     * or check junit5-README.md */
    String sauceUserName = System.getenv("SAUCE_USERNAME");
    String sauceAccessKey = System.getenv("SAUCE_ACCESS_KEY");
    String sauceURL = "https://ondemand.saucelabs.com/wd/hub";

    /**
     * In this section, we will configure our test to run on some specific
     * browser/os combination in Sauce Labs.*/
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("username", sauceUserName);
    capabilities.setCapability("accessKey", sauceAccessKey);
    capabilities.setCapability("browserName", "Safari");
    capabilities.setCapability("platform", "macOS 10.13");
    capabilities.setCapability("version", "11.1");
    capabilities.setCapability("build", "Onboarding Sample App - Java-Junit5");
    capabilities.setCapability("name", "2-user-site");

    /**
     * In this section, we set the Remote WebDriver to run on Sauce Labs, and pass the capabilities.
     * Then we perform some actions on an application.
     * For this script, enter in your application's URL in place of 'https://www.saucedemo.com'. */

    /** If you're accessing the EU data center, use the following endpoint:.
     * https://ondemand.eu-central-1.saucelabs.com/wd/hub
     * */
    driver = new RemoteWebDriver(new URL(sauceURL), capabilities);
    driver.navigate().to("https://www.saucedemo.com");
    //assertTrue(true);
}